如何在 EntityFrameworkCore InMemory 中包含对象属性

How to include object properties in EntityFrameworkCore InMemory

我想用 EntityFramework.InMemory 测试 DbContext,但是当我尝试包含所有对象属性时,它们都是空的,我真的不知道为什么。

我有一个 UnitOfWorkLocator 负责创建和 return 相同的 UnitOfWork。

public static class UnitOfWorkLocator
{
     public static Func<UnitOfWork> UnitOfWorkFactory;

     public static UnitOfWork GetUnitOfWork()
     {
         return UnitOfWorkFactory();
     }
}

所以在每次测试中 class 我都会这样做:

contextOptions = new DbContextOptionsBuilder<SchoolLibraryContext>()
                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                .Options;
UnitOfWorkLocator.UnitOfWorkFactory = () => new UnitOfWork(contextOptions);

借书:

public class LendedBook: EntityBase
{
    public virtual Book Book
    {
        get;
        set;
    }
    public virtual Student Student
    {
        get;
        set;
    }
    public virtual DateInterval DateInterval
    {
        get;
        set;
    }
    public bool Returned
    {
        get;
        set;
    }
    public bool Canceled
    {
        get;
        set;
    }
}

存储库中的方法:

public LendedBook GetLendedBookById(Guid lendedBookId)
{
    return schoolLibraryContext.LendedBooks.Include(book => book.Book)
       .Include(student => student.Student)
       .Include(dateInterval => dateInterval.DateInterval)
       .FirstOrDefault(lendedBook => lendedBook.Id == lendedBookId) ??
       throw new EntityNotFoundException(typeof(LendedBook).Name);
}

EntityBase class 负责使用此方法将实体保存在数据库中:

public void Save()
{
      using (var unitOfWork = UnitOfWorkLocator.GetUnitOfWork())
      {
            unitOfWork.AddOrUpdate(this);
            unitOfWork.Commit();
      }
}

EntityBase 也有 Id 属性:

public Guid Id { get; set; }

在LendedBook上执行的初始化和Save方法:

var student = new Student("Sebastian", "Odegrad")
{
     Email = "email@domain.com"
};
var dateInterval = new DateInterval
{
     StartDate = new DateTime(2018, 08, 01),
     EndDate = new DateTime(2018, 08, 30)
};
var lendedBook = new LendedBook
{
     Student = student,
     DateInterval = dateInterval
};
libranian = new Libranian("Wilskinson", "Martin");

student.Save();
dateInterval.Save();
lendedBook.Save();

那么,如何使用 EFCore.InMemory 正确包含所有对象属性?

我找到了一个解决方案:

我更改了 UnitOfWork 构造函数的参数以接受 DbContext 而不是 DbContextOptions。我还从 EntityBase 中删除了 Save() 方法,并在 LendedBookRepository 中创建了 AddLendedBook。我认为这种方法更加干净和可测试。