0

i have this scenario when creating a new record it also recreates it's association.

User newUser = new User();
newUser.UserGroupID = 1;
newUser.UserGroup = UserGroup.Find(1);

using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
    context.Users.Add(newUser);
    context.SaveChanges();
}

when i save it, it creates a new User record, and so is a new UserGroup record.

1
  • 2
    Just a side note - you do not have to set UserGroup And UserGroupId - one of both is enough - EF will handle it. Commented Jul 4, 2013 at 14:42

3 Answers 3

1

You are using different contexts for UserGroup.Find() and Users.Add() this is not okay - use the same context for both and it will work fine.

using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
    var newUser = new context.Users.CreateNew();
    newUser.UserGroup = context.UserGroup.Find(1);

    context.Users.Add(newUser);
    context.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is the same issue as in this question. Either use the same context for Find and SaveChanges, or, if that can't be done for some reason, use Attach() to attach the found UserGroup to the new context.

Comments

0

you need to tell the context that your entity is an existing entity:

User newUser = new User();
newUser.UserGroupID = 1;
newUser.UserGroup = UserGroup.Find(1);

using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
    context.UserGroups.Attach(newUser.UserGroup);
    context.Users.Add(newUser);
    context.SaveChanges();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.