简体   繁体   中英

Entity Framework recreating new record

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.

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();
}

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM