我有一個DbModel
配置,如下所示:爲什麼我的DbModelBuilder配置忽略從DbSet映射實體<T> .SqlQuery?
modelBuilder.Entity<WishlistLine>()
.HasKey(w => w.PersistenceKey)
.Property(w => w.PersistenceKey)
.HasColumnName("WishlistLineId");
我必須通過以下兩種方法運行一個查詢:
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();
}
我可以「拯救」 WishlistLines
到通過EF數據庫中沒有任何問題。當我運行此查詢,雖然我得到這個錯誤:
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.
我瞭解,使用DbSet<T>.SqlQuery()
將返回的數據映射到實體,但它似乎被忽略了DbModel
配置。從錯誤消息中判斷(猜測)錯誤的數據閱讀器正在被使用。
so:
A)我是否做錯了什麼?
B)有沒有辦法使用EF的DbModel
-aware實體映射器?
您需要在您的DbContext運行查詢。順便說一句,爲什麼你需要一個SQL查詢來檢索數據?爲什麼不在你的rDBContext中使用Linq? – zsong