2009-09-08 27 views
0

我有一些問題試圖映射使用流利NHibernate的實體。流利的NHibernate:奇怪的列映射行爲

我有三個實體,像這樣:

public class Product 
{ 
    public virtual Guid Id { get; set; } 
    public virtual Category Category { get; set; } 
    public virtual Seller Seller { get; set; } 
} 

public class Seller 
{ 
    public virtual Guid Id { get; set; } 
    public virtual IList<Product> Products { get; set; } 
} 

public class Category 
{ 
    public virtual int Id { get; set; } 
} 

注意,類別用於其ID int類型,而其他類使用的GUID。

我的映射類是這樣的:

public sealed class ProductDbMap : ClassMap<Product> 
{ 
    public ProductDbMap() 
    { 
     Id(x => x.Id); 

     References(x => x.Seller) 
      .Not.Nullable(); 

     References(x => x.Category, "Category") 
      .Nullable(); 
    } 
} 

public sealed class SellerDbMap : ClassMap<Seller> 
{ 
    public SellerDbMap() 
    { 
     Id(x => x.Id); 

     HasMany(x => x.Products); 
    } 
} 

public sealed class CategoryDbMap : ClassMap<Category> 
{ 
    public CategoryDbMap() 
    { 
     Id(x => x.Id); 
    } 
} 

最後,我有以下的約定,指定參考ID列的命名方式:

public class ReferenceConventions : IReferenceConvention 
{ 
    public bool Accept(IManyToOnePart target) 
    { 
     return true; 
    } 

    public void Apply(IManyToOnePart target) 
    { 
     target.ColumnName(target.Property.Name + "Id"); 
    } 
} 

這裏是NHibernate的決定如何產生表格:

create table Product (
    Id UNIQUEIDENTIFIER not null, 
    SellerId UNIQUEIDENTIFIER not null, 
    CategoryId INTEGER, 
    Seller_id UNIQUEIDENTIFIER, 
    primary key (Id) 
) 

create table Seller (
    Id UNIQUEIDENTIFIER not null, 
    primary key (Id) 
) 

create table Category (
    Id integer, 
    primary key (Id) 
) 

生成有幾個錯誤產品表:

  1. 「SellerId」列由於某種原因被複制;重複的列不遵循我的命名約定。
  2. 我想通過向參考方法提供一個「Category」的值來覆蓋「CategoryId」列的命名約定。但是,該表仍然使用該約定。

這是怎麼回事?

回答

2

在這裏回答我自己的問題。

1)重複的列出現是因爲我需要在ReferenceConvention之外添加一個HasManyConvention。兩者一起工作只會導致創建列。對於HasManyConvention的代碼是:

public class HasManyConventions : IHasManyConvention 
{ 
    public bool Accept(IOneToManyPart target) 
    { 
     return true; 
    } 

    public void Apply(IOneToManyPart target) 
    { 
     target.KeyColumnNames.Add(target.EntityType.Name + "Id"); 
    } 
} 

2)第二個問題似乎是一個很奇怪的用流利的NHibernate的約定。這是我的理解,ClassMap的列名應該重寫約定(這是合乎邏輯的,並且更有用)。但是,這似乎並沒有發生。該問題可以通過檢查大會中列名是否爲空來解決:

public class ReferenceConventions : IReferenceConvention 
{ 
    public bool Accept(IManyToOnePart target) 
    { 
     return true; 
    } 

    public void Apply(IManyToOnePart target) 
    { 
     if (target.GetColumnName() == null) 
      target.ColumnName(target.Property.Name + "Id"); 
    } 
}