entity-framework - Entity Framework T4 : POCOs implement generic interface?

标签 entity-framework entity-framework-6 t4 edmx

我修改了MyContext.tt T4 模板,以便所有生成的 POCO 实现 IDataEntity :

<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
<#=codeStringGenerator.EntityClassOpening(entity)#> : IDataEntity
{ ... }

是否可以生成 POCO,以便它们实现通用 IDataEntity<T>哪里T给定表的主键列的类型是什么?

例如,如果主键为 Customer表是 Guid ,那么生成的类将是:

public class Customer : IDataEntity<Guid>
{ ... }

我正在使用 Entity Framework 6。

最佳答案

我正在使用这样的东西:

<#@ Import Namespace="System" #>
<#@ Import Namespace="System.Data" #>
<#@ Import Namespace="System.Data.SqlClient" #>

...

<#
    DataSet primaryKeys = GetPrimaryKeys();
    string primaryKeyName = GetPrimaryKey(primaryKeys, codeStringGenerator.EntityClassOpening(entity));

    public class <#=code.Escape(entity)#> : IDataEntity<<#= primaryKeyName #>>
#>

...

<#+
    string GetPrimaryKey(DataSet data, string tableName)
    {
        if (data != null && data.Tables != null && data.Tables[0].Rows != null)
        {
            foreach (DataRow row in data.Tables[0].Rows)
            {
                if ((row[0] as string) == tableName)
                {
                    return (row[1] as string);
                }
            }
        }
        return null;
    }

    DataSet GetPrimaryKeys()
    {
        string connectionString = "...";
        SqlConnection connection = new SqlConnection(connectionString);
        string getAllExtendedProperties = @"              
                SELECT table_name, column_name
                FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
                WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1";

        SqlCommand sqlSelectCommand = new SqlCommand(getAllExtendedProperties, connection);
        try
        {
            SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
            mySqlDataAdapter.SelectCommand = sqlSelectCommand;
            DataSet data = new DataSet();
            if (connection.State != ConnectionState.Open) connection.Open();
            mySqlDataAdapter.Fill(data);
            return data;
        }
        catch (Exception ex)
        {
            //...
            return null;
        }
        finally
        {
            connection.Close();
        }
    }    
#>

关于entity-framework - Entity Framework T4 : POCOs implement generic interface?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21545430/

相关文章:

c# - 尝试添加项目时在 Entity Framework 中出错

C# Entity Framework 属性(有时)为空

c# - T4 模板调试正常但在正常运行模式下出错

visual-studio - 使用 T4 获取项目或相关目录

c# - 返回带有列表对象的列表对象

c# - 是否可以为新行设置 DataGridRow 单元格的值?

sql - Visual Studio 2012 Linq to SQL 可视化工具

c# - 使用 Npgsql 和 Entity Framework 将 bool 属性存储为整数

.net - 您可以从 .NET 应用程序内部处理 T4 模板吗?

java - JPA hibernate : An entity copy [xxx] was already assigned to a different entity [yyyyy]