Stu*_*ffe 6 entity-framework circular-dependency ef-core-2.0
我有一个由两个实体组成的相当简单的数据模型:
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; }
}
Run Code Online (Sandbox Code Playgroud)
和
public class Location
{
public int Id { get; set; }
[Required]
public int UserId { get; set; }
public string Address { get; set; }
public User User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
为了成功运行迁移,我需要以下模型构建器代码:
builder.Entity<Location>()
.HasOne(x => x.User)
.WithMany(x => x.Locations)
.HasForeignKey(x => x.UserId);
Run Code Online (Sandbox Code Playgroud)
正如我期望的那样,这已经生成了一个数据库,以及我将如何使用它。但是,由于以下循环依赖项错误,我无法保存实体:
InvalidOperationException:无法保存更改,因为在要保存的数据中检测到循环依赖性:'ForeignKey:用户{'CurrentLocationId'}->位置{'Id'} ToPrincipal:CurrentLocation,ForeignKey:位置{'UserId'}->用户{'Id'} ToDependent:位置ToPrincipal:用户'。
EF Core 2.0中是否可以解决此问题?
我可以通过更改数据模型来解决这个问题,但这是首选方法,因为我可以使用数据库约束来确保所有位置都链接回用户,并且每个用户都必须设置CurrentLocation。我知道它可以解决问题,但是我真的不能在CurrentLocation字段中允许使用null!
我用来尝试和存储用户的代码如下(出于演示目的而简化):
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();
Run Code Online (Sandbox Code Playgroud)
而且我也尝试过
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();
Run Code Online (Sandbox Code Playgroud)
但是错误仍然相同。可以通过某种精美的ModelBuilder覆盖来解决此问题吗?还是我仅限于更改数据模型/在我本不应该允许空值的地方允许空值?
提前致谢!
归档时间: |
|
查看次数: |
1525 次 |
最近记录: |