开发者

Fluent NHibernate: Initializing OneToMany collections

开发者 https://www.devze.com 2023-04-03 05:33 出处:网络
I have a standard one-to-many relationship between two objects, Person and Order.This is represented in my object model as a collection of orders on the Person.This manife开发者_如何学JAVAsts itself i

I have a standard one-to-many relationship between two objects, Person and Order. This is represented in my object model as a collection of orders on the Person. This manife开发者_如何学JAVAsts itself in the database as a "PersonID" foreign key on the Order Table.

When a person has no orders, the Orders collection property on the Person is being returned as null. I was expecting it to have been initialized with an empty collection, to avoid the need for null checking code all over the place.

Is there any way to configure nHibernate (fluently) to return an empty collection, instead of null when there are not yet any items in the database for that collection?

Thanks for any help.


You should new up your Order collection in the constructor of the Person class.

public class Person 
{
     public Person()
     {
         Orders = new List<Order>();
     }

     ...

     public virtual IList<Order> Orders { get; set; }
     ...
}

If a Person has no orders now, it will return an empty collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号