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

c# entity-framework-6 foreign-keys

Question

How can I declare in EF 6 that a property of an entity is a foreign key reference, making it impossible to remove the entity being referred even if it is a parent in another entity?

This 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; }
}

the class mentioned above, theparentId is a mention of anotherUser .

My current code is as follows:

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

The following error is appearing for me:

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

ZZZ_tmp
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