今天在學習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在執行查詢填充實體時,出現了異常,只需要將屬性類型
與字段類型匹配對應問題就不會出現了!
最后感謝園子和原文章小泉哥哥!
記錄一下。也可以用來以后溫習!