如何在实体框架中为属性创建最小值

本文关键字:属性 创建 最小值 框架 实体 | 更新日期: 2023-09-27 18:16:43

如何为下面给出的方法编写一个实体的moq特别是对于像db.Entry(driver).Property(x => x.EffectiveDate).IsModified = true; ?

这样的属性
public bool UpdateEffectiveDate(int driverId, DateTime effectiveDate, string UserId)
{
    db myentity = new myentity();
    Driver driver = db.Drivers.Find(driverId);
    driver.EffectiveDate = effectiveDate;
    driver.LastModifiedBy = UserId;
    driver.LastModifiedDate = DateTime.Now;
    db.Drivers.Attach(driver);
    db.Entry(driver).Property(x => x.EffectiveDate).IsModified = true;
    db.Entry(driver).Property(x => x.LastModifiedBy).IsModified = true;
    db.Entry(driver).Property(x => x.LastModifiedDate).IsModified = true;
    return (db.SaveChanges() > 0);
}

如何在实体框架中为属性创建最小值

你需要改变你的方法来使用方法注入。

public bool UpdateEffectiveDate(db aEntity, int driverId, DateTime effectiveDate, string UserId)
{
    //db myentity = new myentity();
    Driver driver = aEntity.Drivers.Find(driverId);
    driver.EffectiveDate = effectiveDate;
    driver.LastModifiedBy = UserId;
    driver.LastModifiedDate = DateTime.Now;
    aEntity.Drivers.Attach(driver);
    aEntity.Entry(driver).Property(x => x.EffectiveDate).IsModified = true;
    aEntity.Entry(driver).Property(x => x.LastModifiedBy).IsModified = true;
    aEntity.Entry(driver).Property(x => x.LastModifiedDate).IsModified = true;
    return (aEntity.SaveChanges() > 0);
}

然后你像这样设置你的测试…

  var _MockEntity = new Mock<db>();
  var _MockDrivers = new Mock<Drivers>();
  var _MockDriver = new Mock<Driver>();
  _MockEntity.Setup(x => x.Drivers()).Returns(() => _MockDrivers.Object);
  _MockDrivers.Setup(x => x.Find(123)).Returns(() => _MockDriver.Object); 
  _MockDriver.SetupProperty(x => x.EffectiveDate);
  _MockDriver.SetupProperty(x => x.LastModifiedBy);  
  _MockDriver.SetupProperty(x => x.LastModifiedDate); 
  myClass.UpdateEffectiveDate(_MockEntity.Object, 123, samedatehere,"test");
  var _Driver = _MockDriver.Object;
  var _Expected =  samedatehere;
  var _Actual =_Driver.EffectiveDate;
  Assert.Equal(_Expected, _Actual);  

几乎所有你需要学习如何模拟moq https://github.com/Moq/moq4/wiki/Quickstart