Home > other >  Entity Framework - foreign key property not changed after db.SaveChanges();
Entity Framework - foreign key property not changed after db.SaveChanges();

Time:12-30

I have a database(code first) with 2 tables User and Category. Every user is assigned to one category:

This code works:

User userEntity = db.Users.FirstOrDefault(u => u.UserId == model.UserId);
Category categoryEntity = db.Category.FirstOrDefault(c => c.CategoryId == model.Category.CategoryId);
userEntity.Category = categoryEntity;
db.SaveChanges();

This code does not work:

db.Entry(model).Entity.Category.CategoryId = model.Category.CategoryId;
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();

My DbContext is:

public DbSet<User> Users { get; set; }
public DbSet<Category> Category { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>().HasRequired<Category>(s => s.Category);
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Why is that?

At first I had code that does not work marked as in the first example.

After a changes I corrected the error and my code works marked as second example.

I just want to know the reason..

CodePudding user response:

your first code is not working because the Category property is a navigation property that represents the relationship between the User and Category entities, but it does not represent a column in the database.

you need to add this line userEntity.CategoryId = categoryEntity.CategoryId; in your first code

CodePudding user response:

I think you would need to attach the change to your DBContext before saving change, something like this:

_context.Users.Attach(your_modifed_user_object);

By doing this, you tell Entity Framework (EF) that your object has a new change, and EF will be able to 'track' the change to generate the correct SQL command.

Note that you need to use Attach because your user object is an existing object in the database, so EF needs to track it.

More about Attach here: https://learn.microsoft.com/en-us/ef/ef6/saving/change-tracking/entity-state#attaching-an-existing-entity-to-the-context

CodePudding user response:

There is no CategoryId property in User entity. There is Category property, that refers to Category entity. The code 1 (where userEntity is used) works well, and there is no need to change anything. code 2 does not work, and that's the one that has to be changed.

  •  Tags:  
  • c#
  • Related