2009-09-08 26 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"); 
    } 
}