简体   繁体   English

如何在EF 6中使用流畅的api设置外键

[英]How to use the fluent api to set a foreign key in EF 6

In EF 6, how can I specify that an entity's property is a foreign key reference, such that the entity being referenced cannot be removed if it is a parent in another entity? 在EF 6中,如何指定一个实体的属性是一个外键引用,这样如果该引用的实体是另一个实体的父级,则不能删除该实体?

Here is my class: 这是我的课:

public class User
{
    [Key]
    public int id { get; set; }
    public int parentId { get; set; }
    [ForeignKey("parentId")]
    public virtual User user { get; set; }
}

In the above class, the parentId is a reference to another User . 在上面的类中, parentId是对另一个User的引用。

Here is my current code: 这是我当前的代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().HasKey(x => x.id);
    modelBuilder.Entity<User>().HasOptional<User>(x => x.user);
    base.OnModelCreating(modelBuilder);
}

I am getting the following error: 我收到以下错误:

One or more validation errors were detected during model generation: 在模型生成期间检测到一个或多个验证错误:

DataService.Context.User_user: : Multiplicity conflicts with the referential constraint in Role 'User_user_Target' in relationship 'User_user'. DataService.Context.User_user::多重性与关系“ User_user”中的角色“ User_user_Target”中的引用约束冲突。 Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. 因为从属角色中的所有属性都是不可为空的,所以主体角色的多重性必须为'1'。

Maped to the navigation property, you should add virtual property of type User than map to: 映射到导航属性,您应该将用户类型比映射的虚拟属性添加到:

public class User 
{
 [Key] public int id { get; set; }     
 public int UserId { get; set; }
 public virtual User User{get;set;}
}
// ...
 modelBuilder.Entity<User>().HasOptional<User>(x=> x.User);

Read more about relation-ships here 在这里阅读更多有关关系的信息

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

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