entity framework并行一对多关系

我一直在寻找尝试在EF中创建一个并行的一对多关系。 这是我的意思:

我有两个类,交易和用户:

public class Transaction { public int ID { get; set; } public string ExecutorID { get; set; } public virtual User Executor { get; set; } public string ConsumerID { get; set; } public virtual User Consumer { get; set; } } public class User { public UserRole Role { get; set; } public string Name { get; set; } public string Id { get; set; } public string Pin { get; set; } public virtual List ExecutedTransactions { get; set; } public virtual List Transactions { get; set; } } 

如果您还没有看到它,我在对象, TransactionsExecuted Transactions之间有两个链接。 我的问题是如何告诉EF区分这两者?

事务应该指向User.ID == Transaction.ConsumerIDExecutedTransactions所有Transaction ,其中User.ID == Transaction.ExecutorID

以下是FoodBook源自Item

 public class Person { public int Id { get; set; } public string Name { get; set; } public ICollection Foods { get; set; } public ICollection Books { get; set; } } public abstract class Item { public int Id { get; set; } public string Name { get; set; } } public class Food : Item { public int CookedById { get; set; } [ForeignKey("CookedById")] public Person CookedBy { get; set; } } public class Book : Item { public int AuthorId { get; set; } [ForeignKey("AuthorId")] public Person Author { get; set; } } 

选项每个层次结构的表

 public class AppContext : DbContext { public DbSet People { get; set; } public DbSet Items { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().HasMany(p => p.Foods).WithRequired(f => f.CookedBy).WillCascadeOnDelete(false); } } 

结果将是2个表 ,表PersonItem具有自动Discriminator列,将填充FoodBook

要查询,您需要按类型过滤Items

 using (var context = new AppContext()) { var foods = context.Items.Where(item => item is Food).ToArray(); var books = context.Items.Where(item => item is Book).ToArray(); } 

选项B每个混凝土类别的表格

 public class AppContext : DbContext { public DbSet People { get; set; } public DbSet Foods { get; set; } public DbSet Books { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().HasMany(p => p.Foods).WithRequired(f => f.CookedBy).WillCascadeOnDelete(false); } } 

结果将是3个表 ,表PersonFoodBook

要查询,您可以直接从食品和书籍。

 using (var context = new AppContext()) { var foods = context.Foods.ToArray(); var books = context.Books.ToArray(); } 

选项C每种类型的表

 public class AppContext : DbContext { public DbSet People { get; set; } public DbSet Items { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().HasMany(p => p.Foods).WithRequired(f => f.CookedBy).WillCascadeOnDelete(false); modelBuilder.Entity().ToTable("Foods"); modelBuilder.Entity().ToTable("Books"); } } 

结果将是4个表 ,表PersonItemFoodBook 。 Table Food and Book将与表Ttem

查询与Table Per Hierarchy相同。