ENTITY FRAMEWORK INSERTING A MANY-TO-MANY RELATIONSHIP BETWEEN TWO EXISTING OBJECTS WHILE UPDATING

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 1340  View(s)
Ratings:
Rate this:
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.ApplyPropertyChanges("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.

  1. Pravesh Singh

    Post:101

    Points:709
    Re: Entity framework inserting a many-to-many relationship between two existing objects while updating

    Hey Chintoo!

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

      Modified On Sep-28-2013 06:37:42 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!