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