bileyazan
bileyazan

Reputation: 352

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:

Upvotes: 0

Views: 2129

Answers (2)

Nicholas Murray
Nicholas Murray

Reputation: 13509

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();
    }
}

Upvotes: 1

Jamie Ide
Jamie Ide

Reputation: 49301

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.

Upvotes: 0

Related Questions