Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework extra properties are not populated by DbContext.Database.SqlQuery

When I add extra properties to a EF auto-generated class by using an extra partial class, these properties are not populated or filled when running queries against the database.

Example:

Auto-Generated class Person:

public partial class Person
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

My own partial class

public partial class Person
{
    public string DisplayName{ get; set; }
}

When I make the following query:

"SELECT *, (FirstName + LastName) AS DisplayName FROM [Person]" 

and use

DbContext.Database.SqlQuery(typePerson, SQL, null)

the Id, FirstName and LastName are populated but not the DisplayName.

However when I create a whole new class called MyPerson

public partial class MyPerson
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DisplayName{ get; set; }
}

And run the same query with the type of MyPerson the DisplayName is populated as well.

Can anyone explain this or tell me how I can fix this problem so I can use Partials instead of having to create new classes/types.

Download an example: https://www.dropbox.com/s/dayrv0jzuoju9q3/StackOverflow_EF_ExtraProperties.zip?dl=0

UPDATE 2015-12-28: While reading through other stackoverflow and Codeproject forums I found another ways to get it to work:

1) Using Typebuilder (http://www.codeproject.com/Articles/206416/Use-dynamic-type-in-Entity-Framework-SqlQuery) but due to all sort of project dependencies I had problems finding already created types and not blowing up the memory;

2) Best option so far: using inheritance.

When I create another class with just this lines:

class Person_Reflect : Person { }

I can use the following code (it will ignore the mapping in the EDMX file and use reflection:

List<EF.Person> listPerson = dbEntities.Database.SqlQuery<EF.Person_Reflect>(sql, new object[] { }).ToList<EF.Person>();
like image 623
LiQuick.net Avatar asked Dec 24 '15 08:12

LiQuick.net


1 Answers

Best option so far without having to code much and or to do much code review when Database changes occur is to use inheritance.

When I create another class with just this line:

class Person_Reflect : Person { }

I can use the following code (it will ignore the mapping in the EDMX file and use reflection):

List<EF.Person> listPerson = dbEntities.Database.SqlQuery<EF.Person_Reflect>(sql, new object[] { }).ToList<EF.Person>();
like image 97
LiQuick.net Avatar answered Nov 16 '22 04:11

LiQuick.net