FluentNHibernate Lookup Table

2019-07-29 23:29发布

问题:

This is possibly an easy one that I can't seem to get past.

I've created a "Product" class which has a list of "Accessories". Each "Accessory" is just another product referenced by a lookup table.

Table setup:

Product
-------
ProductID int
Name varchar(200)

AccessoryProduct
----------------
ID int
ParentProductID int
ChildProductID int

I'd like to be able to access this list of accessories in a manner such as:

foreach(Product p in product.Accessories)
 string s = p.Name;

The part I'm stumped on is the FluentNHibernate mapping for this lookup. Within my ProductMap class, I have the following mapping:

Id(x => x.ProductID);
Map(x => x.Name);
HasMany(x => x.Accessories)
 .Table("AccessoryProduct")
 .KeyColumn("ParentProductID")
 .Cascade.None()
 .Inverse()
 .LazyLoad();

This is currently creating a query that looks for "ParentProductID" within the Product table instead of the lookup table(AccessoryProduct).

Is there a simple method I'm missing that allows for a fluent mapping of a lookup table?

Any assistance is appreciated, even if it involves the xml mapping. I should be able to figure out the fluent side.

回答1:

You need a Many-to-Many relationship.

Try:

 HasManyToMany(x => x.Accessories)
 .Table("AccessoryProduct")
 .ParentKeyColumn("ParentProductID")
 .ChildKeyColumn("ChildProductID")
 .Cascade.None()
 .Inverse()
 .LazyLoad();