我有一個簡單的多對一關系:
public class Company
{
public IEnumerable<User> Users { get; set; }
public int Id { get; set; }
}
public class User
{
public int CompanyId { get; set; }
[Required]
public Company Company { get; set; }
public int Id { get; set; }
}
我還嘗試將我的用戶定義為以下內容(沒有成功):
public class User
{
[Required]
[ForeignKey("Company")]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
public int Id { get; set; }
}
我有以下方法將新用戶添加到公司:
public async Task<bool> Add(User user)
{
try
{
await this.context.Set<User>().AddAsync(user);
await this.context.SaveChangesAsync();
return true;
}
catch (Exception)
{
return false;
}
}
我這樣稱呼這個方法:
var company = await this.companyService.Get(1); // this works
if (company == null)
{
return;
}
await this.userService.Add(
new User
{
CompanyId = company.Id,
Company = company, // I also tried to remove this line - no effect
});
我的 DbContext 看起來像這樣:
public class AppContext : IdentityDbContext
{
public AppContext(DbContextOptions<AppContext> options)
: base(options)
{
}
public DbSet<Company> Company { get; set; }
public DbSet<User> User { get; set; }
}
既然我已經解釋了這個場景,那么問題就來了。當我將用戶添加到公司時,所有條目都將被洗掉。我所說的“洗掉”是什么意思?整個表“user”是空的,沒有任何條目。在我添加用戶并檢查之前,company我可以看到所有用戶。如果我在插入后再次獲取公司,該屬性Users將回傳一個空串列(非空)。這也會影響值的洗掉和更新。我已經坐在這里解決這個問題 3 天了,完全不知道我做錯了什么。
uj5u.com熱心網友回復:
試試這個類(如果你使用 ef core 5 ,你可以省略資料注釋)
public class User
{
[Key]
public int Id { get; set; }
[Required]
public int? CompanyId { get; set; }
[ForeignKey(nameof(CompanyId ))]
[InverseProperty("Users")]
public virtual Company Company { get; set; }
}
public class Company
{
[Key]
public int Id { get; set; }
[InverseProperty(nameof(User.Company))]
public virtual ICollection<User> Users { get; set; }
}
和代碼
var company = await this.companyService.Get(1);
await this.userService.Add(new User { CompanyId = company.Id});
public async Task<bool> Add(User user)
{
try
{
context.Set<User>().Add(user);
await context.SaveChangesAsync();
return true;
}
catch (Exception)
{
return false;
}
}
uj5u.com熱心網友回復:
經過 30 小時的除錯,我發現了問題。它與 EF 無關(我在某種程度上期望它,因為我從字面上復制并粘貼了整個檔案 5 次)。
也許有人有類似的問題,所以我在這里發布我的答案,但請注意,這對我的用例非常特定。
我將當前登錄的用戶存盤在ProtectedSessionStorage 中,如下所示:
await this.protectedSessionStorage.SetAsync("user", await this.userService.Get(id));
無論出于何種原因(我又搜索了 2 個小時),我的一些屬性被忽略并且沒有正確存盤(即 property Company.Users),即使我沒有使用任何解釋這種行為的注釋。當我再次加載這個確切的用戶時,出于其他一些未知的原因,EF 認為(因為Company.Users屬性丟失)該公司沒有任何用戶。同樣,檔案中沒有描述這種行為,我發現實際上沒有人遇到這個特定的問題,所以我可能已經做了一些描述這種行為的事情。
解決方案:從 Newtonsoft獲取Json.NET,對其進行序列化,然后將序列化的字串存盤在受保護的會話存盤中。我真的只是改變了這一點,一切都按預期作業。當然,當我訪問存盤時,我必須反序列化所有內容。
await this.protectedSessionStorage.SetAsync("user", JsonConvert.SerializeObject(await this.userService.Get(id)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359187.html
