开发者

entity framework inserting a many-to-many relationship between two existing objects while updating

开发者 https://www.devze.com 2022-12-23 03:10 出处:网络
I\'m trying to do this: using(var context = new SampleEntities()) { User user = select a user from database;

I'm trying to do this:

using(var context = new SampleEntities())
{
     User user = select a user from database;

     //Update user's properties
     user.Username = ...
     user.Website = ...

     //Add a role
     Role role = select a role from  database  
     //trying to insert into table UserRoles which has columns (UserID, RoleID)  
     user.Roles.Add(role); 

     //Apply property changes
     context.ApplyProper开发者_如何学运维tyChanges("Users", user);
     context.SaveChanges();
}

However, I get an exception telling me that "The existing object in the ObjectContext is in the Added state" and can't "ApplyPropertyChanges". If "ApplyPropertyChanges()" is removed, it adds a User.

What orders should these methods be called? I don't need to do them separately right? Thanks.


It doesn't look to me like your User object is detached, so you shouldn't need to call ApplyPropertyChanges().

0

精彩评论

暂无评论...
验证码 换一张
取 消