开发者

Fluent NHibernate - Many To One Relation

开发者 https://www.devze.com 2023-01-08 17:30 出处:网络
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?

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

精彩评论

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