2014-02-18 59 views
3

我的程序中有很多通用方法,它們將一些生成的實體作爲參數。因此,類似的方法:實體框架6中的基類?

public void DoHerpDerp<EntityType>() 

雖然這是罰款和做這項工作,我的方法,用戶仍然可以通過任何他們想要的泛型參數(和應用程序崩潰)。我想嚴格限制它們到實體生成對象(我使用數據庫優先方法)。我想寫的東西,如:

public void DoHerpDerp<EntityType>() where EntityType : BaseEntity 

有這樣類作爲BaseEntity,如果不是一個,我該如何解決此問題?不,我不會寫200個實現接口的部分類。

回答

6

您可以通過調整T4模板來更改實體的生成。

這裏是用於生成類聲明的T4模板(例如Model.tt)的相關部分,例如, 「partial class MyEntity」:

public string EntityClassOpening(EntityType entity) 
{ 
    return string.Format(
     CultureInfo.InvariantCulture, 
     "{0} {1}partial class {2}{3}", 
     Accessibility.ForType(entity), 
     _code.SpaceAfter(_code.AbstractOption(entity)), 
     _code.Escape(entity), 
     _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); 
} 

public string EntityClassOpening(EntityType entity) 
{ 
    return string.Format(
     CultureInfo.InvariantCulture, 
     "{0} {1}partial class {2}{3}{4}", 
     Accessibility.ForType(entity), 
     _code.SpaceAfter(_code.AbstractOption(entity)), 
     _code.Escape(entity), 
     _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)), 
     string.IsNullOrEmpty(_code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))) ? _code.StringBefore(" : ", "BaseClass") : ""); 
} 

在這個例子中,作爲一個子類的BaseClass,你可以實現你生成每一個不具有超一流級希望。

+0

謝謝,這就像一個魅力工作! – Davor