Fluent NHibernate - Many To One Relation
There is a table of Products and Categories. Many products have one category. So, in Product mapping, how can I write the correct code to map with its category?
In Product class:
- Is it 开发者_开发知识库something like: References(x => x.Category).Column........
If you mean a Category has many Products you need something like this:
public class ProductMap : ClassMap<Product>
{
public ProductMap ()
{
Table("products");
Id(x => x.Id);
Map(x => x.Name)
References(x => x.Category).Column("CategoryId");
}
}
public class CategoryMap : ClassMap<Category>
{
public CategoryMap()
{
Table("categories");
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Products).LazyLoad().Inverse().Cascade.All();
}
}
If this is a many-to-one relationship from Products to Categories such that a Product has at most one Category, the mapping is:
References(x => x.Category, "CategoryId");
assuming CategoryId is the foreign key in the Products table. However, your question states that "Many products have one category." so it's unclear what the relationship is.
精彩评论