在POCO Template t4生成器中查找属性是主键

won*_*rld 10 t4

我正在使用VS 2012附带的POCO t4模板生成器.我做了一些更改以包含Entity.Name,但我无法弄清楚主键.

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)));
}
Run Code Online (Sandbox Code Playgroud)

我找不到从EntityType对象层次结构中查找主键的方法.它暴露了属性,但该属性没有任何说法它是主键.

任何帮助赞赏.

Ian*_*Ian 17

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

首先你需要:

using System.ComponentModel.DataAnnotations;
Run Code Online (Sandbox Code Playgroud)

我把它放在靠近顶部的// ----块下面.

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

    var simpleProperties = typeMapper.GetSimpleProperties(entity);
    if (simpleProperties.Any())
    {
        foreach (var edmProperty in simpleProperties)
        {
#>
 <#if (ef.IsKey(edmProperty))
   {#>      [Key()]
   <#}#>
    <#=codeStringGenerator.Property(edmProperty)#>
<#
        }
    }
Run Code Online (Sandbox Code Playgroud)


Paw*_*wel 9

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