我有以下实体:
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; }
}
这种关系在流畅的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阻止我在父母双方中引用相同的实体。周围有路吗?
答案 0 :(得分: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);