你能帮我解决多对一关系吗?

Can you help me Many to One Relation for it?

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");

           });

我写了一对多relation.But我需要多对一

一对多和多对一是相同的定义,但这篇文章Configuring One To Many Relationships in Entity Framework Core可以帮助您做到这一点。

以下模型表示公司和员工在依赖实体 (Employee) 中定义了反向导航 属性 但在依赖实体 属性 中没有匹配的外键 属性

注意:您可以从导航中访问外键 属性

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);
    }