我有一个相当简单的数据模型,包含两个实体:
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();
但错误仍然相同.这可以通过某种奇特的模型构建器覆盖来修复吗?或者我是否限制更改我的数据模型/允许空值我不应该真正允许空值?
提前致谢!
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。