I have a DbModel configuration like so:
modelBuilder.Entity<WishlistLine>()
.HasKey(w => w.PersistenceKey)
.Property(w => w.PersistenceKey)
.HasColumnName("WishlistLineId");
I have a query run via the following two methods:
public IEnumerable<WishlistLine> FetchWishlistLinesUsingLogonName(string logonName)
{
return GetFromRawSql(@"
SELECT wl.* FROM WishlistLines wl
INNER JOIN Accounts a ON wl.AccountId = a.AccountId
LEFT JOIN Users u ON u.AccountId = a.AccountId
WHERE u.LogonName = @p0", logonName);
}
protected IEnumerable<TEntity> GetFromRawSql(string sqlQuery, params object[] parameters)
{
return _dbSet.SqlQuery(sqlQuery, parameters).ToList();
}
I can “save” WishlistLines into the database through EF without any problems. When I run this query though I get this error:
The data reader is incompatible with the specified 'DataAccessLayer.DatabaseContext.WishlistLine'. A member of the type, 'PersistenceKey', does not have a corresponding column in the data reader with the same name.
I understood that using DbSet<T>.SqlQuery() would map the returned data to the entities but it seems to be ignoring the DbModel configurations. Judging (guessing) from the error message the wrong data reader is being used.
so:
A) am I doing anything wrong?
B) is there a way to make use of EF’s DbModel-aware entity mapper?
Indeed the column name mapping is ignored when you execute a raw SQL query. Here are two references: This pretty dissatisfying thread only for fun, but the following one with a serious answer from the EF team:
Quote from http://entityframework.codeplex.com/workitem/233:
So, the only workaround seems to be an explicit
ASalias instead of a*in your SQL query that specifies your property name as a column alias: