Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Get list of primary key column names in EF Core

$
0
0
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?


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>