に必要なFKで循環依存、私は2つのエンティティからなる非常に単純なデータモデルがあります:成功した移行を得るために、その後EFコア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; }
}
と
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);
これは、I私はそれが必要なのかと期待しています。しかし、以下の循環依存エラーのためにエンティティを保存できません:
InvalidOperationException:保存するデータに循環依存が検出されたため変更を保存できません: 'ForeignKey:User {' CurrentLocationId '} - >場所{'Id'} ToPrincipal:CurrentLocation、ForeignKey:場所{'UserId'} - >ユーザー{'Id'} ToDependent:場所ToPrincipal:ユーザー '。
EF Core 2.0でこれを回避する方法はありますか?
私はデータモデルを変更することでそれを巡回するいくつかのオプションがありますが、DB制約を使用してすべてのLocationsがUserにリンクし、すべてのユーザがCurrentLocationを設定する必要がある。私はそれが問題を解決するだろうが、私は実際にCurrentLocationフィールドにnullsを許可することはできません知っている!
次のように私は、ユーザーをしようとして保存するために使用しているコードは(デモの目的のために簡略化):
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();
を試してみたが、エラーが残っています同じ。 ModelBuilderの上書きを修正することでこれを修正できますか?それとも、私は自分のデータモデルの変更に制限されていますか?nullを許可するべきではありません。
ありがとうございます!
最小限にUser.CurrentLocationIdをnullにすると、ロケーションを持たないユーザーを挿入してサイクルを中断することができます。 –