Home > database >  Establishing one-to-many relationships between two entities with Entity Framework
Establishing one-to-many relationships between two entities with Entity Framework

Time:11-05

I have a windows form app project in C#. I am using ORM tool that entity framework. I am beginner in EF. I have two entities ( Machine, User ) A user can have multiple machines, but a machine cannot have multiple users. I want to establish relationship like this. But right now my classes just have id and name property. The class structure I've created in its current state is not suitable for the task I mentioned because there is no relationship.

   internal class Machine
   {
       [Key]
       public int id { get; set; }
       public string name { get; set; }         
   }
  internal class User
  {
      [Key]
      public int id { get; set; }
      public string name { get; set; }    
  }

To establish the relationship I mentioned, what class structure do I need to create?

CodePudding user response:

This is what I do

internal class Machine
   {
       [Key]
       public int id { get; set; }
       public string name { get => name; set => name = value; }     
       Public User User {get; set;}    
   }


internal class User
  {
      [Key]
      public int id { get; set; }
      public string name { get => name; set => name = value; }
      Public List<Machine> Machines {get; set;}
  }

And then Add-Migration [name your migration]

Like:Add-Migration one-to-many- relationship-user-machine And Update-Database

CodePudding user response:

First of all, you have to understand what you are trying to achieve.

A user can have multiple machines, but a machine cannot have multiple users

This is called a one-to-many relationship.

Now there are 2 ways achieve this in Entity Framework, you can do it by putting the correct properties over the models AND you can also specify it in the OnModelCreating method when it becomes complex.

Here is what your model should look like:

internal class Machine
{
   [Key]
   public int id { get; set; }
   public string name { get; set; }
   public int UserId { get; set; }  
   public User User { get; set; }
}

internal class User
{
   [Key]
   public int Id { get; set; }
   public string Name { get; set; }
   public ICollection<Machine> Machines { get; set; }
}

In the OnModelCreating method (not necessary for non-complex structure like this one), you will be adding these lines

modelBuilder.Entity<User>()
    .HasMany(e => e.Machines)
    .WithOne(e => e.User)
    .HasForeignKey(e => e.UserId);

Reference from Microsoft Docs: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-many

  • Related