Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a property is Primary Key in POCO Template t4 generator

Tags:

t4

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.

like image 976
wonderful world Avatar asked Dec 27 '12 23:12

wonderful world


3 Answers

I added this to the TypeMapper section, delighted with the results:

public IEnumerable<EdmProperty> GetPrimaryKeyProperties(EntityType type)
{
    return type.KeyMembers.Select(s => (EdmProperty)s);
}
like image 139
Cedric Avatar answered Nov 11 '22 18:11

Cedric


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)#>
<#
        }
    }
like image 44
Ian Avatar answered Nov 11 '22 19:11

Ian


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

like image 9
Pawel Avatar answered Nov 11 '22 17:11

Pawel