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

时间:2018-08-22 08:31:53

标签: entity-framework .net-core entity-framework-core ef-core-2.1 .net-core-2.1

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

我有一个UnitOfWorkLocator,负责创建并返回相同的UnitOfWork。

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

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

因此,在每个测试类中,我都这样做:

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

LendBook:

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类负责使用以下方法将实体保存在数据库中:

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正确包含所有对象属性?

1 个答案:

答案 0 :(得分:0)

我找到了一种解决方案:

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