简体   繁体   English

实体框架忽略属性时添加

[英]Entity Framework Add while ignoring property

Here's the relevant parts of my code: 这是我的代码的相关部分:

public partial class Users
{
   public string Name { get; set; }
   public Guid RoleId { get; set; }
   public virtual Role UserRole {get; set; }
}

public partial class Role
{
   public string RoleName {get; set; }
   public Guid RoleId {get; set; }
}

RoleId is a primary key in the Roles table which has RoleName and RoleId. RoleId是Roles表中具有RoleName和RoleId的主键。 Users has Name and RoleId. 用户具有名称和RoleId。

After setting up the User, I attempt to add them 设置用户后,我尝试添加他们

this.Entities.Users.Add(user);
this.Entities.SaveChanges();

However, I get a DbUpdateException of type Violation of PRIMARY KEY in the Roles table. 但是,我在“角色”表中得到类型为“违反PRIMARY KEY”的DbUpdateException。 From what I am seeing, it is trying to insert the Role attached to the user, which obviously would cause that problem. 从我所看到的,它正在尝试将附加的角色插入用户,这显然会导致该问题。

I tried putting a [NotMapped] attribute on the UserRole, however that did not fix the issue. 我尝试将[NotMapped]属性放在UserRole上,但是并没有解决问题。

EF generated both of those classes. EF生成了这两个类。

Do I need to do some kind of schema change to make it not include UserRole and refactor to use the RoleId in users and reference everything that way, or is there something else that I am missing? 我是否需要进行某种模式更改以使其不包括UserRole并重构为在用户中使用RoleId并以此方式引用所有内容,还是我还缺少其他功能?

EDIT: Did a shallow copy grabbing the required information and it works now. 编辑:做了一个浅表副本获取所需的信息,它现在可以工作。

您可以在EF类设计器的工具窗口中取消映射属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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