Vishnu Babu
Vishnu Babu

Reputation: 1275

Prevent Entity Framework from inserting child object on Parent Insert

I have a model class for user groups. This table will consist of some fixed set of data

public class UserGroup
{
    public int Id { get; set; }

    [Index(IsUnique = true)]
    [StringLength(30)]
    [Required]
    public string UserGroupName { get; set; }
}

and a user class like

 public class User 
 {  
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public UserGroup UserGroup { get; set; }
 }

A user can only belong to one user group. When I try to save a user using the code below, EF tries to create a new user group also, instead of mapping it to an existing one. what am I doing wrong here ? How can I solve this ?

 User user = new User();
  .....
  user.UserGroup =_dbContext.UserGroup.FirstOrDefault(x=>x.Id==1)
 _dbContext.Users.Add(user);
 _dbContext.SaveChanges();

Upvotes: 0

Views: 92

Answers (2)

H.Mikhaeljan
H.Mikhaeljan

Reputation: 813

The issue occurs because of putting in the complete UserGroup instead of setting a reference to the UserGroup.

 public class User 
 {  
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public int UserGroupId {get;set;}
     public UserGroup UserGroup { get; set; }
 }

Add UserGroupId to your User class and instead set the UserGroupId.

 User user = new User();
  .....
  user.UserGroupId =_dbContext.UserGroup.FirstOrDefault(x=>x.Id==1)?.Id;
 _dbContext.Users.Add(user);
 _dbContext.SaveChanges();

Upvotes: 0

Vivek Nuna
Vivek Nuna

Reputation: 1

You need to set the state to Modified. If EF doesn’t track it. Otherwise it will try to insert the Chile entity.

  dbContext.UserGroup.State = EntityState.Modified;

Upvotes: 1

Related Questions