2013-03-25 60 views
1

我试图使用T4来生成下面的代码实体映射表名:获取使用T4

public virtual IList<Frequency> GetAll() 
    { 
     using (var wc = new WCDataClassesDataContext()) 
     { 
      return wc.Frequencies.ToList(); 
     } 
    } 

    public virtual IList<Frequency> GetAll(Expression<Func<Frequency, bool>> whereClause) 
    { 
     using (var wc = new WCDataClassesDataContext()) 
     { 
      return wc.Frequencies.Where(whereClause).ToList(); 
     } 
    } 

在T4我使用:

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) 
{ 
    fileManager.StartNewFile(entity.Name + "BaseFinder.cs"); 
    BeginNamespace(code); 
#> 

<#=codeStringGenerator.UsingDirectives(inHeader: false)#> 
using System.Linq; 
using System.Linq.Expressions; 
<#=codeStringGenerator.EntityClassOpening(entity)#> 
{ 

    public virtual IList<<#=entity.Name #>> GetAll() 
    { 
     using (var wc = new WCDataClassesDataContext()) 
     { 
      return wc.[[Frequencies]].ToList(); 
     } 
    } 

    public virtual IList<<#=entity.Name #>> GetAll(Expression<Func<<#=entity.Name #>, bool>> whereClause) 
    { 
     using (var wc = new WCDataClassesDataContext()) 
     { 
      return wc.[[Frequencies]].Where(whereClause).ToList(); 
     } 
    } 

...... 
} 

代替[频率] ]我想要实体映射到的主表名称。 我想要设置各种可以在类中轻松使用的getter。

你能告诉我这样做的解决方案是什么,或者有其他方法可以做到这一点?

希望你明白了我的观点。

谢谢。

回答

0

看起来你已经有了实体类型,所以我认为你很接近 - 你所需要做的就是获得具有多重关系的导航属性,并且应该设置。

喜欢的东西:

EntityType et = entity.GetType(); 
foreach(var navProp in et.NavigationProperties.Where(np=>np.DeclaringType == et 
     && np.RelationshipMultiplicity == RelationshipMultiplicity.Many)) 
{ 
    string s = string.Format("public virtual IList<{0}> GetAll() ...", 
          navProp.ToEndMember.GetEntityType().Name); 

} 

实体框架DB-第一发电机已经做的这一番风味;如果你在EDMX下进行挖掘,你应该看到一个*.Context.tt或类似的东西。在那里,搜索NavigationProperty,有一个代码字符串助手方法来生成类似的东西。

+0

是的,这可以帮助我猜,将有一个看看这个。有什么资源可以找到所有在T4中使用的帮助器方法或类描述/类的文档? – Umair 2013-04-04 10:51:42

+0

我还没有找到一个,但这并不意味着不存在。在添加EDMX和EF Utility'ttinclude'后,VS添加的'* .Context.tt'文件让我有最好的运气,通常位于'C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ Common7 \ IDE \ Extensions \ Microsoft \ Entity Framework \ Tools \ Templates \ Includes'。 – Ross 2013-04-04 15:14:30

+0

另外,对于它的价值,你可以使用'MetadataWorkspace'在非T4上下文中做到这一点。 [这](http://stackoverflow.com/questions/10817289/entity-framework-finding-foreign-keys)的问题可能会有所帮助。 – Ross 2013-04-04 15:22:05