2012-09-05 26 views
4

我有一個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實體映射器?

+0

您需要在您的DbContext運行查詢。順便說一句,爲什麼你需要一個SQL查詢來檢索數據?爲什麼不在你的rDBContext中使用Linq? – zsong

回答

2

事實上,當您執行原始SQL查詢時,列名稱映射將被忽略。這裏有兩個引用:This很不滿意線程只爲了好玩,但下面一個從EF團隊認真的回答:

報價從http://entityframework.codeplex.com/workitem/233

The SqlQuery method is designed not to take any mapping into account, including mapping that is applied using attributes. It simply matches the column names from the results with property names in the object. If the column names don't match you will need to use a column alias (AS keyword in SQL Server) to rename the column in the results.

We agree that it would be useful to have the option to make SqlQuery honor Column attributes so we're keeping this issue open and putting it on our backlog for future consideration.

所以,唯一的解決方法似乎是一個明確AS別名,而不是在你的SQL查詢*指定你的屬性名作爲列別名:

return GetFromRawSql(@" 
    SELECT wl.WishlistLineId AS PersistenceKey, 
      wl.SomeOtherColumn AS SomeOtherProperty, 
      ... 
    ..." 
    // ... 
0

我發現另一種解決方案是比較乾淨。在我的模型,我有一個漂亮的名字,我想使用公共屬性,並用完全相同的名稱私人屬性,如數據庫,並在公立的吸氣返回專用密鑰值,像這樣:

public class KeywordsStatistic 
{ 
    public string Keyword { get { return lib_motcle; } } 
    public int NumActions { get { return nbrActions; } } 

    private string lib_motcle { get; set; } 
    private int nbrActions { get; set; } 
} 

當然,這將需要進行修改,如果值需要更新,但原理是一樣的...

HTH

相關問題