加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

entity-framework – EF Core 2.0 – 循环依赖,两端都需要FK

发布时间:2020-12-14 04:50:41 所属栏目:百科 来源:网络整理
导读:我有一个相当简单的数据模型,包含两个实体: public class User{ public int Id { get; set; } public string Name { get; set; } public int CurrentLocationId { get; set; } public ListLocation Locations { get; set; } public Location CurrentLocatio
我有一个相当简单的数据模型,包含两个实体:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CurrentLocationId { get; set; }

    public List<Location> Locations { get; set; }
    public Location CurrentLocation { get; set; }
}

public class Location
{
    public int Id { get; set; }
    [Required]
    public int UserId { get; set; }
    public string Address { get; set; }

    public User User { get; set; }
}

然后,为了成功运行迁移,我需要以下模型构建器代码:

builder.Entity<Location>()
       .HasOne(x => x.User)
       .WithMany(x => x.Locations)
       .HasForeignKey(x => x.UserId);

这产生了一个我期望的数据库以及我需要它的方式.但是,由于以下循环依赖性错误,我无法保存实体:

InvalidOperationException:无法保存更改,因为在要保存的数据中检测到循环依赖关系:’ForeignKey:User {‘CurrentLocationId’} – >位置{‘Id’} ToPrincipal:CurrentLocation,ForeignKey:Location {‘UserId’} – >用户{‘Id’} ToDependent:地点ToPrincipal:User’.

在EF Core 2.0中有解决方法吗?

我有一些选项可以通过更改我的数据模型来环绕它,但这是首选方法,因为我可以使用数据库约束来确保所有位置链接回用户,并且每个用户必须设置CurrentLocation.我知道它可以解决问题,但我不能真正允许在CurrentLocation字段上使用空值!

我用来尝试和存储用户的代码如下(为了演示目的而简化):

var location = new Location
{
    Address = "Some address"
};

_context.Locations.Add(location);

var user = new User
{
    Name = "Stu"
};

_context.Users.Add(user);

user.Locations = new List<Location>
{
    location
};

user.CurrentLocation = location;

await _context.SaveChangesAsync();

而我也试过了

var location = new Location
{
    Address = "Some address"
};

var user = new User
{
    Name = "Stu",Locations = new List<Location>
    {
        location
    },CurrentLocation = location
};

_context.Users.Add(user);    
await _context.SaveChangesAsync();

但错误仍然相同.这可以通过某种奇特的模型构建器覆盖来修复吗?或者我是否限制更改我的数据模型/允许空值我不应该真正允许空值?

提前致谢!

解决方法

回答我自己的问题 – 刚检查过,SQL服务器不支持可延迟的约束,所以EF无论如何也无法做到!更改为数据模型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读