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

浪子不回头ぞ 提交于 2019-12-09 00:39:09

问题


If I have a User class that has these properties:

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

    public Guid SecondaryUserPreferenceId { get; set; }
    public virtual DefaultUserPreference SecondaryUserPreference { get; set; }

How can I get this to make via fluent API? When I try to run this it says:

Introducing FOREIGN KEY constraint on table 'Users' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

I've seen a few of these questions but they always involve one single navigation property and one collection. Also the relationship is unidirectional, but it could be bidirectional if it had to be, not sure if that matters.


回答1:


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);


来源:https://stackoverflow.com/questions/17200407/ef-code-first-map-two-navigation-properties-to-the-same-object-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!