Search code examples
c#asp.net-coredatacontext

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

           });

I wrote one to many relation.But i need many to one


Solution

  • One to many and many to one are the same definition but this article Configuring One To Many Relationships in Entity Framework Core can help you to do this.

    The following model represents companies and employees with an inverse navigation property defined in the dependent entity (Employee) but no matching foreign key property in the dependent

    note: you can access the Foreign key from navigation property

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

    A company has many employees, each with one company. That relationship is represented as follows:

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

    It can also be configured by starting with the other end of the relationship:

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