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.
I added this to the TypeMapper section, delighted with the results:
public IEnumerable<EdmProperty> GetPrimaryKeyProperties(EntityType type)
{
return type.KeyMembers.Select(s => (EdmProperty)s);
}
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)#>
<#
}
}
Use EntityType.KeyMembers property to get properties the primary key consists of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With