Entity Framework 4.1 Database First does not add a primary key to the DbContext T4 generated class

强颜欢笑 提交于 2019-12-01 04:12:36
Ladislav Mrnka

T4 Templates doesn't use data annotations because classes generated from templates don't need them. EF also don't need them because mapping is defined in XML files not in code. If you need data annotations you must either:

  • Modify T4 template to use them (this requires understanding of EF metadata model)
  • Don't use templates and use code first instead
  • Use buddy classes to manually add data annotations and hope that scaffolding will recognize them

If someone does want to do this, I found some good interesting templates on james mannings github Those templates have more functionality, but the bit I pulled out of these was:
1) Replace the usings at the top of Entity.tt with

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
<#
    if (efHost.EntityFrameworkVersion >= new Version(4, 4))
    {
       WriteLine("using System.ComponentModel.DataAnnotations.Schema;");
    }
#>

2) Then find this line (that prints out the properties)

    <#= Accessibility.ForProperty(property) #> <#= typeUsage #> <#= code.Escape(property) #> { get; set; }

3) and prepend this template code

    var attributes = new List<string>();
    var isPartOfPrimaryKey = efHost.EntityType.KeyMembers.Contains(property);
    var primaryKeyHasMultipleColumns = efHost.EntityType.KeyMembers.Count > 1;

    if (isPartOfPrimaryKey)
    {
        if (primaryKeyHasMultipleColumns)
        {
            var columnNumber = efHost.EntityType.KeyMembers.IndexOf(property);
            attributes.Add(String.Format("[Key, Column(Order = {0})]", columnNumber));
        }
        else
        {
            attributes.Add("[Key]");
        }
    }
    PushIndent(new string(' ', 8));
    foreach (var attribute in attributes)
    {
        WriteLine(attribute);
    }
    ClearIndent();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!