我修改了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/