Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-to-one-optional self-referencing relationship

I faced the following domain model

public class Transaction
{
    public Guid Id { get; set; }
    public decimal TransactionSum { get; set; }
    public decimal TransactionCurrencyConversionRatio { get; set; }
    public bool IsTransactionApprovedBySystem { get; set; }
    public bool IsTransactionApprovedBySender { get; set; }
    public DateTime TransactionInitiatedDate { get; set; }
    public DateTime ? TransactionApprovedDate { get; set; }
    public TransactionType TransactionType { get; set; }

    public Account SenderAccount { get; set; }
    public Account ReceiverAccount { get; set; }
    public Guid SenderAccountId { get; set; }
    public Guid ReceiverAccountId { get; set; }
    public Transaction CommissionTransactionForRealTransaction { get; set; }
    public Guid ? CommissionTransactionForRealTransactionId { get; set; }
}

It means, that every transaction is Client-to-Client transaction OR CommssionFee transaction(commision for transaction between client-to-client transaction), it described in TransactionType property, which is enum type.

Example: Bob transfer 100$ to Alice, system charge 1$ for this transfer service, so 2 rows added for this operation:

Transaction #XXX1 - 100$ and it has type Client-To-Client and property CommissionTransactionForRealTransaction is NULL, therefore CommissionTransactionForRealTransactionId attribute in table set to NULL.

Transaction #XXX2 - 1$ and it had type CommissionFee, and property CommissionTransactionForRealTransaction is referencing another object, while CommissionTransactionForRealTransactionId in table has some foreign key.

I read documentation and examples in MSDN on EF Core relationship section, but have no idea how to implement 0...1 to 1 self-referencing. I started with this code:

builder.HasOne(p => p.CommissionTransactionForRealTransaction)
    .WithOne(p => p.???);
like image 936
Iskander Raimbaev Avatar asked Dec 17 '22 18:12

Iskander Raimbaev


1 Answers

Write your fluent API configuration as follows:

builder.HasOne(tr => tr.CommissionTransactionForRealTransaction)
       .WithOne().HasForeignKey<Transaction>(tr => tr.CommissionTransactionForRealTransactionId)
       .IsRequired(false);

It should work for you.

like image 194
TanvirArjel Avatar answered Dec 29 '22 05:12

TanvirArjel