現在很多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 > 0) 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實體也擁有數據。