使用存根实体框架更新导致主键违例 [英] Entity Framework Updating with Stub causes Primary Key Violation

查看:104
本文介绍了使用存根实体框架更新导致主键违例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 用户 - 我的实体模型中有很多到许多方式的关系设置: UserCodePK,UserName 
UserGroups - UserCodeFK,GroupCodeFK
组 - GroupCodePK,GroupDescription

我的代码尝试添加一个用户时:

  public static string CreateUser(User user)
{
使用(var dbContext = new DCSEntities())
{
用户u =新用户
{
UserCodePK =NewUser,
txtUserName =新用户名
};

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

我得到的错误是:

 违反PRIMAR Y KEY约束'PK_Groups'。无法在对象'dbo.Groups'中插入重复键。重复的键值是(ADMIN)

基本上说我正在尝试添加组 ADMIN,它已经存在于该表中,我以为通过使用stub,如上所述,我不需要去数据库来获取ADMIN组并将其添加到User对象
任何关于如何摆脱错误的建议?



编辑:我的完成代码基于以下建议(我希望这是正确的



UI方法

  protected void CreateUser()
{
用户user = new User();
user.UserCodePK = txtUserCode.Text;
user.UserName = txtUserName.Text;
列表< 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 = chkListGr oups.Items [i] .Value});
}
}

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

BLL方法

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

DAL方法

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


解决方案

一个很好的主意,与stubs一起工作。您只需要确保EF不会将它们视为新对象,您可以通过将存根附加到上下文来执行。现在,EF不会给出状态添加

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

...

u.Groups.Add(group);

如果 GroupCode 是主键,EF将知道如何关联对象。


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

解决方案

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.

这篇关于使用存根实体框架更新导致主键违例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆