我有以下代码:
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 添加一条新记录。我怎样才能简单地分配角色但不使用变量。我更喜欢给角色名加上一个字符串。
任何的想法?