1. 程式人生 > >EF的主外來鍵查詢 基於EF的資料外來鍵關聯查詢

EF的主外來鍵查詢 基於EF的資料外來鍵關聯查詢

今天在學習EF主外來鍵查詢時,在園子裡找到了一篇基於EF的資料外來鍵關聯查詢的文章,看完後覺得可以試試,

然後就在我的demo中敲了原文章中的"GetItem"方法。如下:

 1   public T Find<T>(Expression<Func<T, bool>> conditions, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy,
 2             params Expression<Func<T, object>>[] includeProperties) where
T : class 3 { 4 var query = conditions ==null?All<T>():All<T>().Where(conditions); 5 if (includeProperties != null && includeProperties.Length > 0) query = includeProperties.Aggregate(query, 6 (current, includeProperty) => current.Include(includeProperty));
7 8 if (orderBy != null) query = orderBy(query); 9 10 return query.FirstOrDefault(); 11 }

看上去感覺良好,也沒啥問題。但是當我啟動專案來驗證這個方法時卻報瞭如下異常....

當時就一臉懵逼!

看著這異常,由於英語比較菜雞我當時就抓住了幾個關鍵詞。

我就去實體中找IsEnable欄位,在U_Power實體中

發現IsEnable 是int型別的,但是資料庫的欄位是bit型別的,問題就找出來了!

在實體對映的時候,下意識將IsEnable寫成了int型別的,應該是布林型別的才對!

最後將IsEnable改成bool型別的,重新啟動,就沒問題了。

 

總結:在實體對映時,與資料庫表字段型別不匹配,導致EF在執行查詢填充實體時,出現了異常,只需要將屬性型別

與欄位型別匹配對應問題就不會出現了!

最後感謝園子和原文章小泉哥哥

記錄一下。也可以用來以後溫習!