当我尝试创建一个集合并同时向它添加一个类别时,我不断得到一个空引用。我忘了什么吗?还是我做错了?
private static void SamepleMethod(ICollectionRepository collectionRepo)
{
Collection collection = new Collection { CollectionName = "Collection" };
Category category = new Category { Collection = collection, CategoryName = "Category" };
category.SetCollection(collection);
collection.AddCategory(category);
collectionRepo.Save(collection);
}
收藏:
public class Collection
{
public virtual int? Id { get; set; }
public virtual string CollectionName { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual void AddCategory(Category category)
{
Categories.Add(category);
category.Collection = this;
}
}
类别:
public class Category
{
public virtual int? Id { get; set; }
public virtual string CategoryName { get; set; }
public virtual Collection Collection { get; set; }
public virtual void SetCollection(Collection collection)
{
Collection = collection;
collection.Categories.Add(this);
}
}
集合.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="ACME.Model"
assembly="ACME.Model">
<class name="Collection" table="Collections" >
<id name="Id" column="CollectionId" type="int" >
<generator class="identity" />
</id>
<set name="Categories" inverse="true" cascade="all">
<key column="CollectionId" />
<one-to-many class="Category"></one-to-many>
</set>
<property name="CollectionName">
<column name="CollectionName" sql-type="nvarchar(50)" />
</property>
类别.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="ACME.Model"
assembly="ACME.Model">
<class name="Category" table="Categories" >
<id name="Id" column="CategoryId" type="int" >
<generator class="identity" />
</id>
<many-to-one name="Collection"
class="Collection"
column="CollectionId"
not-null="true" />
<property name="CategoryName">
<column name="CategoryName" sql-type="nvarchar(50)" />
</property>