0

我有以下代码:

            var roleEditionCNT = new Role { ApplicationName = "TTT", RoleName = "EDITION_CNT" };
            var roleEditionKCD = new Role { ApplicationName = "TTT", RoleName = "EDITION_KCD" };
            var roleEditionInterne = new Role { ApplicationName = "TTT", RoleName = "EDITION_INTERNE" };
            var roleConsultationInterne = new Role { ApplicationName = "TTT", RoleName = "CONSULTATION_INTERNE" };
            var roleConsultationExterne = new Role { ApplicationName = "TTT", RoleName = "CONSULTATION_EXTERNE" };
            var roleAdministrator = new Role { ApplicationName = "TTT", RoleName = "ADMINISTRATOR" };

            new List<Role>
                {
                    roleEditionCNT,
                    roleEditionKCD,
                    roleEditionInterne,
                    roleConsultationInterne,
                    roleConsultationExterne,
                    roleAdministrator
                }.ForEach(b => context.Roles.AddOrUpdate(m => m.RoleName, b));

然后我可以这样做:

var myUser = new User
      {
        Company = "DELTOY",
        FirstName = "BRYAN",
        LastName = "KENETH",
        Roles = new List<Role> { roleEditionCNT }
      };

现在我想修改我分配角色的方式,如下所示:

var myUser = new User
      {
        Company = "DELTOY",
        FirstName = "BRYAN",
        LastName = "KENETH",
        Roles = new List<Role> { new Role { ApplicationName = "TTT", RoleName = "EDITION_CNT" } }
      };

此代码编译成功,但在运行时出现错误:

违反 PRIMARY KEY 约束“PK_Roles”。无法在对象“dbo.Roles”中插入重复键

通过简单地修改上面的代码,系统似乎正在尝试向表 Roles 添加一条新记录。我怎样才能简单地分配角色但不使用变量。我更喜欢给角色名加上一个字符串。

任何的想法?

4

1 回答 1

1

在第二个示例中,您尝试添加具有新角色的用户,而不是将其分配给现有角色。您尝试添加的角色已存在于角色表中。

您可以将 Role 对象放入变量中。

var role = context.First(p => p.RoleName == "EDITION_CNT");

然后将其分配给新用户。

var myUser = new User
      {
        Company = "DELTOY",
        FirstName = "BRYAN",
        LastName = "KENETH",
        Roles = new List<Role> { role } 
      };
于 2013-02-12T09:34:11.203 回答