EF4 Update Entity Without First Getting Entity

前端 未结 3 2015
Happy的楠姐
Happy的楠姐 2020-12-31 10:33

How can I update an entity without having to make a call to select it. If I supply the key for the entity, should it not know to update after SaveChanges() is called on the

相关标签:
3条回答
  • 2020-12-31 11:19

    You can do this in a somewhat artificial way, by adding the entity and changing the EntityState to Modified:

    var user = new User();
    user.Id = 2;
    user.Username = "user.name";
    user.Name = "ABC 123";
    
    context.AddToUsers(user);
    ObjectStateEntry userEntry = context.ObjectStateManager.GetObjectStateEntry(user);
    userEntry.ChangeState(EntityState.Modified);
    
    context.SaveChanges();
    

    In this way you will be telling the ObjectContext to find an entry with Id = 2 and update it rather than adding a new entry to the database.

    0 讨论(0)
  • 2020-12-31 11:22

    Maybe following code work fine.

    var user = new User();
    user.Id = 2;
    context.Users.Attach(user);
    
    user.Username = "user.name";
    user.Name = "ABC 123";
    
    context.SaveChanges();
    
    0 讨论(0)
  • 2020-12-31 11:26

    Didn't you have to select it anyway to get it's data to edit? If you cache it it won't cost you anything getting it again when you save it.

    0 讨论(0)
提交回复
热议问题