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

c# entity-framework-6 foreign-keys

Question

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'.

1
1
3/4/2016 8:15:42 AM

Popular Answer

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

1
3/3/2016 4:14:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow