Simon
Simon

Reputation: 8345

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?

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.

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'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

Upvotes: 1

Views: 1046

Answers (1)

Henka Programmer
Henka Programmer

Reputation: 747

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

Upvotes: 1

Related Questions