嘗試保存實體時出現客戶端錯誤。2個表同時具有一對多和一對零關系,這會導致以下錯誤:無法確定由“用戶”類型的導航屬性“ Group.LockedByUser”表示的關系。手動配置關系,或者使用“ [NotMapped]”屬性或“ OnModelCreating”中的“ EntityTypeBuilder.Ignore”忽略此屬性這些是我目前的情況:用戶實體public class User{ [Key] public int UserId { get; set; } public string Username { get; set; } public int GroupId { get; set; } public Group GroupThisUserBelongsTo { get; set; } public ICollection<Group> GroupsLockedByThisUser { get; set; } public ICollection<Config> Configs { get; set; }}集團實體public class Group{ [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int GroupId { get; set; } public string GroupName { get; set; } public int? LockedByUserId { get; set; } public User LockedByUser { get; set; } public ICollection<User> Users { get; set; }}DbContext1提取modelBuilder.Entity<Group>(entity => { entity.HasOne(d => d.LockedByUser) .WithMany(p => p.GroupsLockedByThisUser) .HasForeignKey(d => d.LockedByUserId); }modelBuilder.Entity<User>(entity => { entity.HasOne(d => d.GroupThisUserBelongsTo) .WithMany(p => p.Users) .HasForeignKey(d => d.GroupId) .OnDelete(DeleteBehavior.ClientSetNull); });配置實體public class Config{ [Key] public int ConfigId { get; set; } public int UserId { get; set; } public string Config { get; set; } public User User { get; set; }}dbContext2提取 modelBuilder.Entity<Config>(entity => { entity.HasOne(d => d.User) .WithMany(p => p.Configs) .HasForeignKey(d => d.UserId); });產生錯誤的代碼如下:var config = new Config { UserId = 123456, Config = "test" }; _dbContext2.Config.Add(config); _dbContext2.SaveChanges();我真的不明白為什么在嘗試保存該實體時會出現客戶端錯誤。錯誤甚至與我要保存的上下文無關。我的外鍵設置正確嗎?Group有很多User-User有一個Group(FK GroupId)User鎖定零個或多個Group(FK LockedByUserId)Config有一個User(FK UserId)
2 回答

RISEBY
TA貢獻1856條經驗 獲得超5個贊
正如所解釋的這個答案,我需要復制的共享關系。
當使用DbContext2
之間的關系User
并Group
沒有定義。
我可以通過使用單個上下文或讓上下文繼承定義所有共享關系的主上下文來解決我的問題。
- 2 回答
- 0 關注
- 267 瀏覽
添加回答
舉報
0/150
提交
取消