2

我有以下实体:

public class User
{
    [Key]
    public int UserId { get; set; }
    virtual public ICollection<Transaction> Transactions { get; set; }
}

public class Transaction
{
    [Key]
    public Int64 TransactionId { get; set; }

    [Required]
    public virtual User Sender {get; set;}

    public virtual User Receiver { get; set; }
}

关系在fluent API中描述

modelBuilder.Entity<User>()
            .HasMany(r => r.Transactions)
            .WithRequired(s => s.Sender);

modelBuilder.Entity<User>()
            .HasMany(r => r.Transactions)
            .WithOptional(r => r.Receiver);

有两个用户,一个是交易的发送者,第二个是接收者。现在,当我向第一个用户添加事务时,一切正常。当第二个用户接受交易并且我将相同的交易添加到其 ICollection 交易中时,它会神奇地从第一个用户中消失,反之亦然。换句话说,EF 阻止我在父母双方中引用同一个实体。有办法解决吗?

4

1 回答 1

1

您需要在用户类中有两个导航属性。

public class User
{
    [Key]
    public int UserId { get; set; }
    virtual public ICollection<Transaction> SenderTransactions { get; set; }
    virtual public ICollection<Transaction> ReceiverTransactions { get; set; }
}

每个导航属性必须在相关类中具有等效的导航属性。

modelBuilder.Entity<User>()
            .HasMany(r => r.SenderTransactions)
            .WithRequired(s => s.Sender);

modelBuilder.Entity<User>()
            .HasMany(r => r.ReceiverTransactions)
            .WithOptional(r => r.Receiver);
于 2013-08-02T07:12:19.577 回答