Finding a property is Primary Key in POCO Template t4 generator

十年热恋 提交于 2019-12-05 18:03:50

问题


I'm using the POCO t4 template generator that comes with VS 2012. I made few changes to include the Entity.Name, but I'm not able to figure out the primary key.

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)));
}

I don't find a way to find the primary key from the EntityType object hierarchy. It exposes properties but the property does not have anything to say it is a primary key.

Any help appreciated.


回答1:


Just in case anyone is trying to do this while migrating RIA services stuff, I'm using the standard dbcontext template in VS2013 and have added two things to the entities template.

first you need:

using System.ComponentModel.DataAnnotations;

I put it just under the //---- block near the top.

Then I modified the bit of code that looks like this. Just search for the first name. My change is ef.IsKey... and adding the Key() attribute.

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



回答2:


Use EntityType.KeyMembers property to get properties the primary key consists of.



来源:https://stackoverflow.com/questions/14062694/finding-a-property-is-primary-key-in-poco-template-t4-generator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!