Finding a property is Primary Key in POCO Template t4 generator
Asked Answered
F

3

11

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.

Flagship answered 27/12, 2012 at 23:34 Comment(0)
L
17

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)#>
<#
        }
    }
Lydialydian answered 8/2, 2014 at 17:11 Comment(2)
I'm finding that on a table which has no keys defined, the template is returning true for IsKey on multiple columns (not all). I need to have a look at what's going on there, but does anyone have any insight?Nimrod
I think isKey checks for relationships in the edm file. They may not be what you're thinking of as a key columnKassandrakassaraba
F
9

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

Freezing answered 15/1, 2013 at 21:5 Comment(2)
This helped. I ended up using EntityType.KeyProperties for my usage. Thanks!Linkwork
@Linkwork could you please share your code you did using EntityType.KeyProperties? Thanks!Handsel
D
2

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

public IEnumerable<EdmProperty> GetPrimaryKeyProperties(EntityType type)
{
    return type.KeyMembers.Select(s => (EdmProperty)s);
}
Dahomey answered 31/1, 2020 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.