具有存储库模式和工作单元的空对象模式

时间:2020-08-08 13:15:36

标签: asp.net-mvc

我正在使用工作单元来检索记录/记录表单数据库,我正在尝试实现某种空对象设计模式,这样我就不必每次都检查返回的对象是否为空。我已经尝试过在线搜索,但是在当前情况下如何最好地实现这一目标,我还没有获得很好的解释,我熟悉Null Object Design Pattern的传统方法,在该方法中,您将创建具有硬编码属性和方法的null副本类。并根据Db中的搜索结果返回类或空类。但是,我认为对于工作单元和存储库模式,此方法无效。这是课程。

public class HR_Setup_Location 
{
   public string Street1 { get; set; }
   public string Street2 { get; set; }
   public string City { get; set; }
   public string State { get; set; }
   public string Country { get; set; } 
   public string FullAddress{
      get { return $"{Street1} {City} {Country}"; }
  }
   [ForeignKey("Setup")]
   public int SetupId { get; set; }
   public virtual Setup Setup { get; set; }
   public virtual ICollection<HR_Setup_OfficeEvent> HR_Setup_OfficeEvents { get; set; }
}

我尝试了以下方法,该方法目前正在完成,但是如果您在类似情况下尝试过类似的操作,则感谢您对方法的反馈。在这种模式下解决空对象的最佳方法是什么。

 public interface ISetupLocationRepository : IRepository<HR_Setup_Location>
{
    HR_Setup_Location GetById(int LocationId);

}

public class SetupLocationRepository : Repository<HR_Setup_Location>, ISetupLocationRepository
{
    private readonly DataBaseContext context;

    public SetupLocationRepository(DataBaseContext context)
        : base(context)
    {
        this.context = context;
    }


    public HR_Setup_Location GetById(int LocationId)
    {
        HR_Setup_Location Obj = context.HR_Setup_Locations.Where(p => p.HR_Setup_LocationId == LocationId).FirstOrDefault();
        if (Obj != null)
        {
            return Obj;
        }
        else
        {
            HR_Setup_Location Obj2 = new HR_Setup_Location()
            {
                HR_Setup_LocationId = -1,
                Street1 = string.Empty,
                Street2 = string.Empty,
                City = string.Empty,
                State = string.Empty,
                Country = string.Empty,
                SetupId = -1,
            };
            Obj2.HR_Setup_OfficeEvents = null;
            return Obj2;
        }
    }

}

然后使用工作单位,我尝试通过致电:

string LocationName = Vacancy.HR_Setup_LocationId.HasValue ? unitOfWork.SetupLocations.GetById(Vacancy.HR_Setup_LocationId.Value).FullAddress : "";

因此,基本上,如果没有基于id的它将返回一个空字符串,并且如果传递了id但该记录在DataBase中不再可用,则空对象的Fulladdress会返回空

0 个答案:

没有答案