context.MyContext.SqlQuery() skips mapping logic from context's OnModelCreating()?

.net c# entity-framework entity-framework-6 postgresql

Question

I've just started using EntityFramework 6 and I'm still trying some scenarios out. I have overridden the OnModelCreating() method in my context class, and have some logic regarding some column name mappings to properties like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema("public");

    modelBuilder.Entity<Ninja>().Property(x => x.DateOfBirth).HasColumnName("date_of_birth");
}

As you can see the property name is DateOfBirth, and the appropriate column in the DB is date_of_birth. Now when I'm adding/inserting new data in the DB this mapping works fine. And when I'm querying/retrieving data like this:

var ninja = context.Ninjas.FirstOrDefault(n => n.Name.StartsWith("Kacy"));

It works fine.

But when I want to use a DB(postgre 10) function to retrieve the data:

private static void RetrieveDataWithStoredProc()
{
    using (var context = new NinjaContext())
    {
        context.Database.Log = Console.WriteLine;
        var ninjas = context.Ninjas.SqlQuery("select * from get_old_ninjas()").ToList();
    }
}

I get the following exception:

The data reader is incompatible with the specified 'NinjaDomain.DataModel.Ninja'.
A member of the type, 'DateOfBirth', does not have a corresponding column in the data reader with the same name.

Which means it doesn't take into consideration the logic in the modelbuilder regarding the column name of the DateOfBirth property. If I add explicit mapping logic after the SqlQuery, it will work...

My question is why doesn't this method consider the logic already in place in the OnModelCreating method like all other cases do ?

1
0
2/5/2019 2:22:42 PM

Popular Answer

why doesn't this method consider the logic already in place in the OnModelCreating method like all other cases do ?

That is a limitation in EF6. EF Core respects your column mappings when loading from raw SQL queries:

The column names in the result set must match the column names that properties are mapped to. Note this is different from EF6 where property/column mapping was ignored for raw SQL queries and result set column names had to match the property names.

Raw SQL Queries (EF Core)

0
2/5/2019 5:07:06 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow