Entity Framework Updating with Stub causes Primary Key Violation

二次信任 提交于 2019-12-11 06:55:53

问题


I have the following common tables with the relationships setup in a many to many fashion in my entity model:

Users - UserCodePK, UserName
UserGroups - UserCodeFK,GroupCodeFK
Groups - GroupCodePK,GroupDescription

My Code when trying to add a user:

public static string CreateUser(User user)
{
    using (var dbContext = new DCSEntities())
    {
        User u = new User
                {
                    UserCodePK = "NewUser",
                    txtUserName = "New User Name
                };

        u.Groups.Add(new UserGroup {GroupCode = "ADMIN"});
        u.Groups.Add(new UserGroup {GroupCode = "SUPER"});
        dbContext.Users.AddObject(user);
        dbContext.SaveChanges();
        }
}   

The error that I'm getting is :

"Violation of PRIMARY KEY constraint 'PK_Groups'. Cannot insert duplicate key in object 'dbo.Groups'. The duplicate key value is (ADMIN)"

Basically saying that I'm trying to add the group "ADMIN", which already exists in that table. I thought that by using the stub as above, that I won't need to go the database to fetch the "ADMIN" group and add it to the User object. Any advice on how to get rid of the error?

EDIT: My Completed Code Based on the Suggestions Below(I hope this is in the right place?)

UI Method

protected void CreateUser()
{
    User user = new User();
    user.UserCodePK = txtUserCode.Text;
    user.UserName = txtUserName.Text;                
    List<UserGroup> userGroups = new List<UserGroup>();
    for (int i = 0; i < chkListGroups.Items.Count; i++)
    {
        if (chkListGroups.Items[i].Selected == true)
        {
            userGroups.Add(new UserGroup { GroupCodePK = chkListGroups.Items[i].Value });
        }
    }

    string userCode = BLL.UserFunctions.CreateUser(user, userGroups);
}

BLL Method

public static string CreateUser(User user, List<UserGroup> userGroups)
{
    return UserDAL.CreateUser(user,userGroups);
}

DAL Method

public static string CreateUser(User user,List<UserGroup> userGroups)
{
    using (var dbContext = new DCSEntities())
    {
        foreach (UserGroup g in userGroups)
        {
            var ug = new UserGroup { GroupCode = g.GroupCode };
            dbContext.UserGroups.Attach(ug);
            user.UserGroups.Add(ug);
        }
        dbContext.Users.AddObject(user);
        dbContext.SaveChanges();
        return user.UserCode;
    }
}

回答1:


It's a good idea to work with stubs. You only have to make sure that EF won't see them as new object, which you can do by attaching the stub to the context. Now EF will not give it the status Added.

var adminGroup = new UserGroup {GroupCode = "ADMIN"};
db.Groups.Attach(adminGroup);

...

u.Groups.Add(group);

If GroupCode is the primary key, EF will know how to associate the objects.



来源:https://stackoverflow.com/questions/22786315/entity-framework-updating-with-stub-causes-primary-key-violation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!