我有兩個班級的關系。
class ClassA {
[Required]
int Id { get; set; }
[Required]
public int OtherId { get; set; }
[ForeignKey("OtherId")]
public ClassB? Other{ get; set; }
}
class ClassB {
[Required]
int Id { get; set; }
public IEnumerable<ClassA> Others { get; set; } = new List<ClassA>();
}
當我插入一個物件時,ClassA我會這樣做:
await this.Context.Set<ClassA>().AddAsync(new ClassA() { OtherId = 2 } );
await this.Context.SaveChangesAsync();
這在實時資料庫 (Azure SQL DB) 上完美運行。當我添加這樣的類并稍后從資料庫中獲取它時(例如,在 之后SaveChangesAsync),我得到了物件,包括 object ClassA.Other。
另一方面,當我在記憶體資料庫上運行代碼時,它不起作用!插入步驟有效,但不驗證 ID ( ClassA.OtherId) 是否存在。這意味著,我可以ClassA.OtherId毫無問題地將 設定為“12345”,即使我沒有ClassB. 如果我插入一個有效的ClassA.OtherId,它也可以作業,但是當我從資料庫中獲取物件時,ClassA.Other它是空的。
Just to clarify, why I write ClassB? Other instead of ClassB Other. This is only a simplified version of the code, I tested quickly, but in our production environment, we include/exclude certain fields from certain queries for performance reasons. Therefore, it is possible that the property might be null at certain times.
uj5u.com熱心網友回復:
大多數 In-memory Testdoubles 在這方面都有一些缺陷,而是嘗試使用 SQlite Provider,因為它的行為更像是一個真實的資料庫
配置示例:
public static class EfDbContextSqliteBuilderConfigurationFactory
{
internal static Action<DbContextOptionsBuilder> GetSqliteDatabaseOption()
{
const string tempDataBaseFolder = "Database";
EnsureSqliteTempDatabaseFolderExists(tempDataBaseFolder);
return c => c.UseSqlite(new SqliteConnection($"DataSource={tempDataBaseFolder}\\{Guid.NewGuid()}.db"));
}
private static void EnsureSqliteTempDatabaseFolderExists(string tempDataBaseFolder)
{
if (!Directory.Exists(tempDataBaseFolder))
{
Directory.CreateDirectory(tempDataBaseFolder);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/456790.html
