Null value objects in NHibernate

三世轮回 提交于 2019-12-05 01:34:27

I don't have any definitive answers creating a method/property accessor that isn't mapped, and that returns a default/null-object if the actual address is null.

public Address GetAddressOrDefault()
{
  return Address ?? new NullAddress();
}

Or similar to the first, create a wrapper for your Address that you use in the view.

public class AddressViewData
{
  private Address address;

  public AddressViewData(Address address)
  {
    this.address = address ?? new NullAddress();
  }

  // expose all address properties as pass-throughs
  public string Street
  {
    get { return address.Street; }
  }
}

Thanks to James' ideas (see his answer and comments) I have modified the Address property of my Person entity from:

public virtual string Address { get; set; }

to:

private Address _address;
public virtual Address Address
{
    get { return _address ?? new Address(); }
    set { _address = value; }
}

This has solved my problem, it works, and it seems to work with NHibernate. Yey!

In some cases it is very easy to write a NHibernate custom type. Instead of setting the component to null, it would return the null object. I did this in some cases, then you can forget about nulls.

Example of a composite user type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!