Reputation: 201
public class Product : EntityBase<Product, int>, IAggregateRoot
{
public virtual string ProductName { get; set; }
public virtual List<ProductDetail> Description { get; set; }
}
public class ProductDetail : EntityBase<ProductDetail, int>, IAggregateRoot
{
public virtual string Description { get; set; }
public virtual Product Product { get; set; }
}
The above Product Entity has multiple ProductDetails. My mapping is given below;
public class ProductMap : ClassMapping<Product>
{
public ProductMap()
{
Lazy(false);
Table("Product");
Id(x => x.ID, map => { map.Column("ID"); map.Generator(Generators.Native); });
Property(x => x.ProductName, map => map.NotNullable(true));
Bag(x => x.Description, m => {
m.Inverse(true); // Is collection inverse?
m.Cascade(Cascade.All); //set cascade strategy
m.Key(k => k.Column(col => col.Name("ProductID"))); //foreign key in Detail table
}, a => a.OneToMany());
}
}
public class ProductDetailMap : ClassMapping<ProductDetail>
{
public ProductDetailMap()
{
Lazy(false);
Table("ProductDetail");
Id(x => x.ID, map => { map.Column("ID"); map.Generator(Generators.Native); });
Property(x => x.Description, map => map.NotNullable(false));
ManyToOne(x => x.Product, x =>
{
x.Column("ProductID");
});
}
}
When Iam saving this; Iam getting below error.
An exception of type 'NHibernate.PropertyAccessException' occurred in NHibernate.dll but was not handled in user code Additional information: Invalid Cast (check your mapping for property type mismatches);
Upvotes: 1
Views: 788
Reputation: 123861
For mapping collections, we must use interfaces (IList<>
)
public class Product : EntityBase<Product, int>, IAggregateRoot
{
public virtual string ProductName { get; set; }
//public virtual List<ProductDetail> Description { get; set; }
public virtual IList<ProductDetail> Description { get; set; }
}
The NHibernate will inject its own IList<>
implementation - which is not a child of List
... That is needed for proxying... lazy loading
Upvotes: 1