2014-02-18 58 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