EF代码首先,将两个导航属性映射到相同的对象类型 [英] EF Code First, map two navigation properties to the same object type

查看:124
本文介绍了EF代码首先,将两个导航属性映射到相同的对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个具有这些属性的用户类:

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

如何通过流畅的API获得这个?当我尝试运行它时,它说:

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


在表'用户'上引入FOREIGN KEY约束可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
无法创建约束。看到以前的错误。

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.

推荐答案

默认情况下与Cascade Delete建立关系。创建从一个实体到另一个类型的两个关系尝试创建两个级联删除关系,数据库将抛出您看到的错误。

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.

使用Code-First Fluent在一个或两个关系中删除级联删除的配置:

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

这篇关于EF代码首先,将两个导航属性映射到相同的对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆