2012-12-27 34 views
10

我正在使用VS 2012自带的POCO t4模板生成器。我对Entity.Name做了一些更改,但我无法弄清楚首要的关键。查找属性是POCO模板中的主键t4生成器

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

我找不到从EntityType对象层次结构中找到主键的方法。它公开属性,但该属性没有任何可以说它是主键。

任何帮助表示赞赏。

回答

13

为了防止任何人在迁移RIA服务时尝试这样做,我在VS2013中使用了标准的dbcontext模板,并在实体模板中添加了两件事。

首先你需要:

using System.ComponentModel.DataAnnotations; 

我把它只是在靠近顶端处// ----块。

然后我修改了看起来像这样的代码位。只需搜索名字。我的更改是ef.IsKey ...并添加Key()属性。

var simpleProperties = typeMapper.GetSimpleProperties(entity); 
    if (simpleProperties.Any()) 
    { 
     foreach (var edmProperty in simpleProperties) 
     { 
#> 
<#if (ef.IsKey(edmProperty)) 
    {#>  [Key()] 
    <#}#> 
    <#=codeStringGenerator.Property(edmProperty)#> 
<# 
     } 
    } 
+0

我发现在没有定义键的表上,模板在多列(不是全部)上返回IsKey。我需要看看那里发生了什么,但有没有人有任何见解? –

9

使用EntityType.KeyMembers属性获取主键所包含的属性。

+1

这有帮助。我结束了使用EntityType.KeyProperties我的用法。谢谢! – TravisWhidden

+0

@TravisWhidden你能分享你使用EntityType.KeyProperties的代码吗?谢谢! –