EF Code First, map two navigation properties to the same object type

后端 未结 1 1702
遥遥无期
遥遥无期 2021-01-06 00:42

If I have a User class that has these properties:

    public Guid UserPreferenceId { get; set; }
    public virtual DefaultUserPreference UserP         


        
相关标签:
1条回答
  • 2021-01-06 01:18

    Entity Framework creates relationships with Cascade Delete on by default. Creating two relationships from one entity to another type tries to create two cascade-delete relationships, which the database will throw the error you saw for.

    Use the Code-First Fluent Configuration to remove the Cascade Delete on one or both of the relationships:

    modelBuilder.Entity<User>()
        .HasOptional(u => u.UserPreference)
        .WithMany()
        .WillCascadeOnDelete(false);
    modelBuilder.Entity<User>()
        .HasOptional(u => u.SecondaryUserPreference)
        .WithMany()
        .WillCascadeOnDelete(false);
    
    0 讨论(0)
提交回复
热议问题