0

I was trying my hands on NHibernate and Fluent NHiberate. I wrote two classes as follows:

public class Product
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual decimal Price { get; set; }
}

public class ShoppingCart
{
    public virtual int Id { get; set; }
    public IList<Product> Products { get; set; }

    public decimal CartTotal
    {
        get { return Products.Aggregate(0m, (c,x)=>  c + x.Price; ); }
    }

    public ShoppingCart()
    {
        Products = new List<Product>();
    }
}

I want to map Product and ShoppingCart but I don't want any ShoppingCart.Id as key in Products table. How can I define map using Fluent NHibernate?

PS:- I have tried mapping Category and SucCategory using self-referencing category. But I am not able to wrap my head around ShoppingCart and Product problem. Also I want to use MS Sql Server CE 4.0.

TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188

1 Answers1

4

I think, you want a many-to-many relationship. This can be done in Fluent with a mapping like this:

public class ShoppingCartMap : ClassMap<ShoppingCart>
{
    public ShoppingCartMap()
    {
        HasManyToMany(x => x.Products).Table("ShoppingCartToProduct");
        // Other properties follow...
    }
}

This will generate a table named "ShoppingCartToProduct" with two foreign key columns (one to Product.Id and one to ShoppingCart.Id).

rumpelstiefel
  • 466
  • 3
  • 5