我有一个相当简单的数据模型,包含两个实体: public class User{ public int Id { get; set; } public string Name { get; set; } public int CurrentLocationId { get; set; } public ListLocation Locations { get; set; } public Loca
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无论如何也无法做到!更改为数据模型.