如何在连接表(Fluent NHibernate)上使用NHibernate ManyToMany和属性(列)

时间:2010-10-14 20:46:38

标签: c# .net nhibernate fluent-nhibernate

我有以下类,我需要NHibernate才能很好地发挥作用。我该怎么做?

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

我正在使用流畅的映射,并且HasManyToMany不适用于此(我可以告诉)。我目前正在使用HasMany,然后在模型中做一些LINQ查询(yuck)。

提前致谢。

凯尔

2 个答案:

答案 0 :(得分:4)

不知道如何在Fluent中执行此操作,但由于您将数据存储在连接表中,因此您需要从CustomerPricing到Customer和Product进行多对一操作。在hbm.xml中,CustomerPricing的映射看起来像

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

然后在您的Customer类(或两者中,如果需要)中添加:

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

答案 1 :(得分:1)

试试这个

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

将客户映射为

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

和产品映射为

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