2013-12-17 42 views
0

我試圖用我的實體類映射Id屬性和反射使用FluentNHibernate由反射映射Id屬性

我的實體:

public abstract class BaseEntity 
{ 
    public int Id { get; set; } 
} 

public class Entity : BaseEntity 
{ 
    public string Name { get; set; } 
} 

好吧,我的映射類是像上面:

public class BaseMapping<E> : ClassMap<E> 
{ 
    public BaseMapping(string schema, string table) 
    { 
     Schema(schema); 
     Table(table); 
     Id(model => typeof(E).GetProperty("Id", typeof(int)), "Id") 
      .GeneratedBy.Identity() 
      .Not.Nullable(); 
    } 
} 

public class EntityMapping : BaseMapping<Entity> 
{ 
    public EntityMapping() : base("dbo", "Entities") 
    { 
     Map(model => model.Name, "Name") 
      .Length(50) 
      .Insert().Update() 
      .Not.Nullable(); 
    } 
} 

我收到此異常:

{「身份類型必須是完整的( int,long,uint,ulong)「}

當我地圖上EntityMapping類的Id屬性...

Id(model => model.Id, "Id") 
    .GeneratedBy.Identity() 
    .Not.Nullable(); 

它的作品就像一個魅力。但第一次嘗試不起作用。

回答

0

首先,您的物業應標記爲virtual爲您的實體。這是NHibernate框架可以執行其魔術惰性加載voodoo。

這就是說。讓我們假設你所有的實體都從BaseEntity出現。由於這個假設,您可以讓typeparam E瞭解它始終是BaseEntity

一旦你這樣做,你可以重寫BaseMapping<E>方法。

public class BaseMapping<E> : ClassMap<E> 
    where E: BaseEntity 
{ 
    public BaseMapping(string schema, string table) 
    { 
     Schema(schema); 
     Table(table); 
     Id(model => model.Id, "Id"); 
    } 
} 

通過specifing where E: BaseEntity會的E屬性暴露給你的方法。我只測試了這個代碼,直到完成多個實體類型的映射方法。

至於爲什麼你收到你的信息的聲明

typeof(E).GetProperty("Id", typeof(int))

返回一個類型的PropertyInfo,你需要通過成員表達式爲memberExpression參數。通過挖掘FluentNHibernate的源代碼,他們使用Expression通過反射評估爲Member