ASP.NET MVC Core application using EF Core.
In linq to sql this code returns list of database table primary key columns names:
/// <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;
}
In EF Core I tried
var entry = ctx.Entry(dbContextPocoType);
var primaryKey = entry.Metadata.FindPrimaryKey();
IList<string> keys = primaryKey.Properties.Select(x => x.Name).ToList();
return keys;
But this returns C# propery names.
How to get database table column names if EF Core?
Member
52 Points
594 Posts
Get list of primary key column names in EF Core
Jan 21, 2021 11:22 PM|kobruleht|LINK