How to use NHibernate ManyToMany with properties (columns) on Join Table (Fluent NHibernate)

陌路散爱 提交于 2019-12-11 12:18:50

问题


I have the following classes that I need NHibernate to play nicely with. How do I do it?

public class Customer
{
   public int ID { get; set; }
   public string Name {get;set;}
}

public class Product
{
   public int ID { get; set; }
   public string Name {get;set;}
}

public class CustomerPricing
{
   public int ID { get; set; }
   public decimal Price {get;set;}
   public Customer Customer { get; set; }
   public Product Product {get;set;}
   public datetime ExpiresOn { get; set; }
   public string ApprovedBy {get;set;}
}

I am using fluent mappings and the HasManyToMany doesn't work for this (that I can tell). I'm currently working around it by using a HasMany then doing some LINQ queries in the model (yuck).

Thanks in advance.

Kyle


回答1:


No idea how to do it in Fluent, but because you're storing data in the joining table, you'll need to go Many-to-one from CustomerPricing to both Customer and Product. In an hbm.xml, the mapping for CustomerPricing would look like

<many-to-one name="Product" column="ProductID" not-null="true" />
<many-to-one name="Customer" column="CustomerID" not-null="true" />

Then in your Customer class (or in both, if desired) you'd add:

<set name="CustomerPricing" table="CustomerPricing" inverse="true">
        <key column="CustomerID"></key>
        <one-to-many class="CustomerPricing" />
</set>



回答2:


Try this

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Product> ProductsOwned { get; set; }
}

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Customer> Owners { get; set; }
}

with Customer mapping as

 HasManyToMany<Product>(x => x.ProductsOwned) 
.WithTableName("CustomerPricing") 
.WithParentKeyColumn("CustomerID") 
.WithChildKeyColumn("ProductID")

and Product mapping as

 HasManyToMany<Customer>(x => x.Owners) 
.WithTableName("CustomerPricing") 
.WithParentKeyColumn("ProductID") 
.WithChildKeyColumn("CustomerID")


来源:https://stackoverflow.com/questions/3937402/how-to-use-nhibernate-manytomany-with-properties-columns-on-join-table-fluent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!