我一直在寻找尝试在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<Transaction> ExecutedTransactions { get; set; }
public virtual List<Transaction> Transactions { get; set; }
}
如果您还没有看到它,我在对象Transactions
和Executed Transactions
之间有两个链接。我的问题是如何告诉EF区分这两者?
交易应指向所有Transaction
其中User.ID == Transaction.ConsumerID
和ExecutedTransactions
所在的User.ID == Transaction.ExecutorID
答案 0 :(得分:3)
以下是从Food
派生Book
和Item
的类。
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Food> Foods { get; set; }
public ICollection<Book> 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<Person> People { get; set; }
public DbSet<Item> Items { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasMany(p => p.Foods).WithRequired(f => f.CookedBy).WillCascadeOnDelete(false);
}
}
结果将是 2个表格,表格Person
和Item
自动Discriminator
列,其中将填充Food
和{{ 1}}。
要查询,您需要按类型从Book
进行过滤。
Items
选项B每个具体类别的表格
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();
}
结果将是 3个表格,表格public class AppContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Food> Foods { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasMany(p => p.Foods).WithRequired(f => f.CookedBy).WillCascadeOnDelete(false);
}
}
,Person
和Food
。
要查询,您可以直接从食品和书籍中获取。
Book
选项C每类型表
using (var context = new AppContext())
{
var foods = context.Foods.ToArray();
var books = context.Books.ToArray();
}
结果将是 4个表格,表格public class AppContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Item> Items { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasMany(p => p.Foods).WithRequired(f => f.CookedBy).WillCascadeOnDelete(false);
modelBuilder.Entity<Food>().ToTable("Foods");
modelBuilder.Entity<Book>().ToTable("Books");
}
}
,Person
,Item
和Food
。表格Book
和Food
与表格Book
有关。
查询与Table Per Hierarchy相同。