代码之家  ›  专栏  ›  技术社区  ›  Eduard Stefanescu

如何在内存中的EntityFrameworkCore中包含对象属性

  •  0
  • Eduard Stefanescu  · 技术社区  · 7 年前

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

    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);
    

    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; }
    

    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 回复  |  直到 7 年前
        1
  •  0
  •   Eduard Stefanescu    7 年前

    我找到了一个解决方案:

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

    推荐文章