0

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........

2 Answers 2

1

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.