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在执行查询填充实体时,出现了异常,只需要将属性类型

与字段类型匹配对应问题就不会出现了!

最后感谢园子和原文章小泉哥哥

记录一下。也可以用来以后温习!

猜你喜欢

转载自www.cnblogs.com/yangDream/p/10065898.html