Random programming things I'd want to remember

Thursday, September 12, 2013

Entity Framework ignores some fields when pulling data


Let's say I have a class:
public class Bookshelf
{
    public int BookshelfID {get;set;}
    public List<string>BookNames {get;set;}
}

and it corresponds to a table named Bookshelves
CREATE TABLE [dbo].[Bookshelves] (
     BookshelfID INT IDENTITY (1,1) NOT NULL
   , BookNames varchar(MAX)...
   , PRIMARY KEY CLUSTERED ([BookshelfID] ASC)
);

in the database. Let's say we are using Entity Framework (4.0), like so:
public class EFDbContext : DbContext
{
    public DbSet<Bookshelf> Bookshelves {get;set;}
}

When Entity Framework generates the SELECT statement to pull all data from table Books, the resulting SQL will be the following:
    SELECT BookshelfID FROM Bookshelves

totally ignoring the BookNames property. But if you alter the class definition such that the BookNames property is a string, the SQL statement will include BookNames column. I guess Entity Framework only works with basic types and does not trust me with explaining it how to treat the lists. You can use LINQ to Objects to extract whatever you need from BookNames.

The bottom line is: if Entity Framework is ignoring some columns in the table, check two things:
  1. Your class contains the corresponding property, and
  2. The datatype is one of these (MSDN article) primitive types.

No comments: