使用EF Core的ASP.NET Core MVC应用程序。在Linq to SQL中,此代码返回数据库表主键列名称列表:
/// <summary>
/// Database primary key names
/// </summary>
public IList<string> DatabasePrimaryKey(Type dbContextPocoType)
{
List<string> pk = new List<string>();
foreach (PropertyInfo p in dbContextPocoType.GetProperties())
{
var ca = p.GetCustomAttributes(typeof(ColumnAttribute), true);
if (ca.Length == 0) continue;
var atr = (ColumnAttribute)ca.Single();
if (!atr.IsPrimaryKey) continue;
pk.Add(atr.Name);
}
return pk;
}
在 EF Core 中,我尝试过
var entry = ctx.Entry(dbContextPocoType);
var primaryKey = entry.Metadata.FindPrimaryKey();
IList<string> keys = primaryKey.Properties.Select(x => x.Name).ToList();
return keys;
但是这返回了C#属性名称——如何在EF Core中获取数据库表列名?
更新:使用答案,我创建了这个方法:
public IList<string> DatabasePrimaryKey<TPoco>()
{
var entry = ctx.Entry(typeof(TPoco));
var primaryKey = entry.Metadata.FindPrimaryKey();
var entityType = ctx.Model.FindEntityType(typeof(TPoco).Name);
var schema = entityType.GetSchema();
var tableName = entityType.GetTableName();
IList<string> keys = primaryKey.Properties
.Select(x => x.GetColumnName(StoreObjectIdentifier.Table(tableName, schema)))
.ToList();
return keys;
}
这种方法可以改进吗?