modelBuilder.Entity<Food>(food =>
{
food.ToTable("foods");
food.Property(e => e.FoodCategoryId).HasColumnName("food_category_id").IsRequired();
food.HasOne(e => e.FoodCategory).WithMany().HasForeignKey(e =>
e.FoodCategoryId).HasConstraintName("fk_foods_food_categories_id");
});
我写了一对多的关系。但是我需要一对多的关系
答案 0 :(得分:1)
一对多和多对一是相同的定义,但是本文Configuring One To Many Relationships in Entity Framework Core可以帮助您做到这一点。
以下模型表示具有在依赖实体(员工)中定义的反向导航属性但在依赖对象中没有匹配的外键属性的公司和员工
注意:您可以从导航属性访问外键
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Company Company { get; set; }
}
一家公司有很多员工,每个员工只有一个公司。这种关系表示如下:
// This method belongs to your context class which is inherited from DbContext
protected override void OnModelCreating(Modelbuilder modelBuilder)
{
modelBuilder.Entity<Company>()
.HasMany(c => c.Employees)
.WithOne(e => e.Company);
}
也可以从关系的另一端开始进行配置:
// This method belongs to your context class which is inherited from DbContext
protected override void OnModelCreating(Modelbuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOne(e => e.Company)
.WithMany(c => c.Employees);
}