开发者

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:


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜