Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext.Database.SqlQuery returns some null objects

Using Entity Framework 6, the code below queries a table (really, a view) and returns some number of rows. The number of rows is correct, but many of the rows are null, i.e. some of the Licenses objects are null, as seen in the Visual Studio Watch window. I think what is happening is that if any column of a given row in the view contains a null, then the entire row is being set to null. Any ideas on how to get all the correct data?

String query = "select * from dbo.v_Licenses where [Number] like '%ab%'";
System.Data.Entity.Infrastructure.DbRawSqlQuery<Licenses> dbRawSqlQuery = db.Database.SqlQuery<Licenses>(query);
Queryable<Licenses> licenses = dbRawSqlQuery.AsQueryable();
like image 877
Al Lelopath Avatar asked Jun 26 '14 16:06

Al Lelopath


3 Answers

Be sure that License properties'name are identical with columns that are fetched from the select and property type are identical, too.

Like this:

Select CustomerId,Firstname from Customers

public class Customer
{
      public int CustomerId{get;set;}

      public string Firstname {get;set;}
}

and change System.Data.Entity.Infrastructure.DbRawSqlQuery to List

I used this approach a lot and it worked very nice for me.

like image 183
Hamed Khatami Avatar answered Nov 19 '22 02:11

Hamed Khatami


Based on this question it seems like EF (at least at one point) returned null objects if the first column of the result set was null. So rather then selecting * you should explicitly name the columns and ensure that the PK (or some other column) is first.

like image 26
D Stanley Avatar answered Nov 19 '22 03:11

D Stanley


In my case it did not work because I did NOT have the fields as properties. Once I converted the fields to properties it worked just fine.

like image 28
Newbie Avatar answered Nov 19 '22 02:11

Newbie