代码之家  ›  专栏  ›  技术社区  ›  Kyle West

如何在联接表上使用具有属性(列)的NHibernate manytomyne(Fluent NHibernate)

  •  1
  • Kyle West  · 技术社区  · 14 年前

    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 回复  |  直到 14 年前
        1
  •  4
  •   Kendrick    14 年前

    不知道如何用Fluent来实现,但是因为您将数据存储在连接表中,所以您需要从客户定价到客户和产品的多对一。在hbm.xml中,CustomerPricing的映射看起来像

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

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

    <set name="CustomerPricing" table="CustomerPricing" inverse="true">
            <key column="CustomerID"></key>
            <one-to-many class="CustomerPricing" />
    </set>
    
        2
  •  1
  •   anivas    14 年前

    试试这个

    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")