现在很多ORM不自带外键关联的实体查询,比如我查询用户,用时将关联的角色信息查询出来,那么就要进行2次查询,很麻烦。而我现在要做的就是基于EF的外键关联查询。很方便的。

首先,创建基础查询的BaseService

public class BaseService<T> where T : BaseEntity
{
public virtual int Create(T item)
{
using (var db = new DatabaseContext())
{
db.Set<T>().Add(item); try
{
var result = db.SaveChanges(); return result;
}
catch (Exception e)
{
throw e;
}
}
} public virtual T GetItem(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includeProperties)
{
using (var db = new DatabaseContext())
{
var query = db.Set<T>().AsExpandable().AsNoTracking(); if (filter != null) query = query.Where(filter); if (includeProperties != null && includeProperties.Length > ) query = includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty)); if (orderBy != null) query = orderBy(query); return query.FirstOrDefault();
}
}
}

BaseEntity见 基于EF创建数据库迁移

这里只添加了2个方法,一个新增,一个查询单条数据。

GetItem方法的includeProperties参数就是用于引用关联数据。

接下来添加RoleService和UserService类。

  public class RoleService : Base.BaseService<Roles>
{
public static RoleService Default = new RoleService();
}   public class UserService : Base.BaseService<Users>
{
public static UserService Default = new UserService();
}

这2个类都集成BaseService,在没有特殊查询的时候,直接使用BaseService的查询方法。

接下来添加数据

var roleId = Guid.NewGuid();
var result = Service.Service.RoleService.Default.Create(new Roles { Id = roleId, Name = "admin" }); var result = Service.Service.UserService.Default.Create(new Users { Id = Guid.NewGuid(), Name = "admin", RoleId = roleId });

数据有了,接下来就是查询了 。

var user = Service.Service.UserService.Default.GetItem(x => x.Name == "admin", null, x => x.Role);

这些你打开user,发现里面的Role实体也拥有数据。

最新文章

  1. Android获取短信验证码
  2. ASP.NET MVC 异步获取和刷新ExtJS6 TreeStore
  3. XdbxAnalysis
  4. iOS 从Xcode看应用支持横竖屏
  5. LightOJ1018 Brush (IV)(状压DP)
  6. 使用python-openCV对摄像头捕捉的镜头进行二值化并打上文字
  7. 【图文详解】scrapy安装与真的快速上手——爬取豆瓣9分榜单
  8. springmvc简述
  9. php 接收二进制流转换成图片
  10. github在eclipse中的配置
  11. sort功能使用
  12. 网络请求工具--AFNetworking 分类: ios技术 2015-02-03 08:17 76人阅读 评论(0) 收藏
  13. 《程序员修炼之道:从小工到专家》【PDF】下载
  14. hdu1060 Leftmost Digit---求N的N次方的首位(对数)
  15. Netty 核心容器之ByteBuf 结构详解
  16. codeforces#1154F. Shovels Shop (dp)
  17. Svn在工作中的实践感悟
  18. Practice4 阅读《构建之法》6-7章
  19. 【转载】Win10打开U盘提示“文件或目录损坏无法读取”怎么办?
  20. 部署openresty遇到的一些坑

热门文章

  1. linux kernel 模块多文件编译
  2. I.MX6 Linux udev porting
  3. uestc 1722 吴神的表白
  4. http请求返回响应码的意思
  5. jquery生成二维码
  6. javascript实现map的功能(转载)
  7. Creating SharePoint 2010 Event Receivers in Visual Studio 2010
  8. 转载:Hadoop权威指南学习笔记
  9. CSS hack大全
  10. C# 中如何判断某个字符串是否为空的方法 分享了三个方法来判断字