4

In EF 6.1 the mapping API was introduced where we could finally get access to table names and column names. Getting the table name is a very nice change in EF Core, but I have not yet uncovered how to get the column names.

For anyone interested here is how I got the table name in the latest version (RC1)

context.Model.FindEntityType(typeof(T)).SqlServer().TableName

What is the current method to get column names or is this not available yet?

2 Answers 2

6
var columnNames = ctx.Model.FindEntityType(typeof (T))
                           .GetProperties().Select(x => x.SqlServer().ColumnName)
                           .ToList();

Also

var columnNames = ctx.Model.FindEntityType(typeof (T))
                           .GetProperties().Select(x => x.Relational().ColumnName)
                           .ToList();

In EF Core 3.X, .Relational() and .SqlServer() have been replaced and you can simply use:

var columnNames = ctx.Model.FindEntityType(typeof (T))
                           .GetProperties().Select(x => x.GetColumnName())
                           .ToList();
5
  • Can you please explain how it would resolve the issue?
    – Phani
    Feb 1, 2016 at 13:47
  • 1
    This looks perfect, I'll check this out later tonight and see how it works. By the way I am a fan of the z extensions. :) Feb 1, 2016 at 19:50
  • 1
    Nice! Did you know I also have a library for entity framework? I'm sure you will become a fan of it also ;)github.com/zzzprojects/EntityFramework-Plus Feb 1, 2016 at 21:38
  • 1
    Worked perfectly. I didn't realize any of your EF stuff was open source. So commonly people try to wrap everything up and hide the underlying api, I like your style of just extending the objects. That is my preferred approach as well. I ended up doing this to get the property map for something :) var propertiesMap = context.Model.FindEntityType(typeof(T)).GetProperties().ToDictionary(p=>p.Name, p=>p.SqlServer().ColumnName); Feb 3, 2016 at 5:59
  • 1
    Yup, extending make it very simple to use and you feel like it a part of Entity Framework. I try to open source as much as I can but there is still some part I hide for intellectual property. Feb 3, 2016 at 13:16
3

This version doesn't assume SqlServer and can work as well with Npgsql provider as long as data store is relational.

var columnNames = dbContext.Model.FindEntityType(typeof(T))
                  .GetProperties().Select(x => x.Relational().ColumnName);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.