数据结构图以下:css
这次实例比较简单,暂时只设计到上述3张表数据库
SMUser:用于存储用户信息。
Role:用于存储角色信息。
SMUser_Role:用创建用户和角色关系的一直关联表。数据结构
开发工具:visual studio 2015
打开vs2015->新建项目->.NET Core->ASP.NET Core Application(.Net core)
以下图:数据库设计
给本身的项目取个名字,选个路径,就完事了。
而后在本身建立的解决方案里再新增个类库项目,此类库项目用于实现数据库的交互,也是实现EF Core的地方,以下图:ide
DAL项目使用Nuget添加如下引用:工具
Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools
在DAL项目中新建Entities文件夹,该文件夹用于创建与数据库表一一对应的实体类。咱们根据数据库结构,建立一下3个实体类。
SMUser:开发工具
using System; using System.Collections.Generic; namespace SnmiOA.DAL.Entities { public class SMUser { public Guid SMUserId { get; set; } public string SSOUserName { get; set; } public string SSOPassword { get; set; } public string TrueName { get; set; } public bool IsValid { get; set; } public string Mobile { get; set; } public string Email { get; set; } public string UserNo { get; set; } public string EmployeeNo { get; set; } public string QQ { get; set; } public virtual ICollection<SMUserRole> SMUserRoles { get; set; } } }
Role:ui
using System; using System.Collections.Generic; namespace SnmiOA.DAL.Entities { public class Role { public Guid RoleId { get; set; } public string RoleName { get; set; } public int OrderField { get; set; } public virtual ICollection<SMUserRole> SMUserRoles { get; set; } } }
SMUserRole:spa
using System; namespace SnmiOA.DAL.Entities { public class SMUserRole { public Guid SMUserId { get; set; } public Guid RoleId { get; set; } public virtual Role Role { get; set; } public virtual SMUser SMUser { get; set; } } }
在DAL项目下添加SnmiOAContext.cs文件。其代码以下:设计
public class SnmiOAContext : DbContext { public SnmiOAContext(DbContextOptions<SnmiOAContext> options) : base(options) { } public DbSet<SMUser> SMUsers { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<SMUserRole> SMUserRoles { get; set; } }
而后咱们须要添加一下3张表之间的映射关系,经过表结构能够看出来,实际上咱们的SMUser和Role之间是多对多的关系,SMUser_Role是两张表产生的一张中间表,在之前的EF中这两张表能够直接映射多对多的关系。可是在EF Core中目前我尚未发现这种映射关系的写法,多是我阅读的资料还不够,也多是真的没有提供这种映射。后来我就找到个把他们都分别改为一对多的关系来写,发现也是能够的。代码以下:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<SMUserRole>() .ToTable("SMUser_Role") .HasKey(ur => new { ur.RoleId, ur.SMUserId }); modelBuilder.Entity<SMUserRole>() .HasOne(ur => ur.SMUser) .WithMany(u => u.SMUserRoles) .HasForeignKey(ur => ur.SMUserId); modelBuilder.Entity<SMUserRole>() .HasOne(ur => ur.Role) .WithMany(r => r.SMUserRoles) .HasForeignKey(ur => ur.RoleId); modelBuilder.Entity<SMUser>() .ToTable("SMUser") .HasKey(u => u.SMUserId); modelBuilder.Entity<SMUser>() .HasMany(u => u.SMUserRoles) .WithOne(ur => ur.SMUser) .HasForeignKey(u => u.SMUserId); modelBuilder.Entity<Role>() .ToTable("Role") .HasKey(r => r.RoleId); modelBuilder.Entity<Role>() .HasMany(r => r.SMUserRoles) .WithOne(ur => ur.Role) .HasForeignKey(ur => ur.RoleId); }
若是你们有更好的方法,还请告知,谢谢!
最后,别忘记了DBContext的依赖注入。
咱们在APP项目的StartUp文件的ConfigureServices方法中添加如下代码:
services.AddDbContext<SnmiOAContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SnmiOAConnection")));
总体看上去应该是这样:
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddDbContext<SnmiOAContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SnmiOAConnection"))); services.AddMvc(); }
Repository实现
当咱们使用不一样的数据模型和领域模型时,仓储模式特别有用。仓储能够充当数据模型和领域模型之间的中介。在内部,仓储以数据模型的形式和数据库交互,而后给数据访问层之上的应用层返回领域模型。
在咱们这个例子中,由于使用了数据模型做为领域模型,所以,也会返回相同的模型。若是想要使用不一样的数据模型和领域模型,那么须要将数据模型的值映射到领域模型或使用任何映射库执行映射。
如今定义仓储接口IRepository以下:
using System; using System.Linq; using System.Linq.Expressions; namespace SnmiOA.DAL.Repository { public interface IRepository<T> where T :class { IQueryable<T> GetAllList(Expression<Func<T, bool>> predicate = null); T Get(Expression<Func<T, bool>> predicate); void Insert(T entity); void Delete(T entity); void Update(T entity); long Count(); } }
上面的几个方法都是常见的CRUD操做,就不解释了.
而后再实现一个仓储类的泛型基类,用来实现IRepository接口,代码以下:
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Linq.Expressions; namespace SnmiOA.DAL.Repository { public class RepositoryBase<T> : IRepository<T> where T : class { private readonly SnmiOAContext _context = null; private readonly DbSet<T> _dbSet; public RepositoryBase(SnmiOAContext context) { _context = context; _dbSet = _context.Set<T>(); } public long Count() { return _dbSet.LongCount(); } public void Delete(T entity) { _dbSet.Remove(entity); } public T Get(Expression<Func<T, bool>> predicate) { return _dbSet.FirstOrDefault(predicate); } public IQueryable<T> GetAllList(Expression<Func<T, bool>> predicate = null) { if (predicate == null) { return _dbSet; } return _dbSet.Where(predicate); } public void Insert(T entity) { _dbSet.Add(entity); } public void Update(T entity) { _dbSet.Attach(entity); _context.Entry(entity).State = EntityState.Modified; } } }
这样每一个实体类的仓储类实现起来,就很是简单了,以下:
using SnmiOA.DAL.Entities; namespace SnmiOA.DAL.Repository { public class RoleRepository : RepositoryBase<Role> { public RoleRepository(SnmiOAContext context) : base(context) { } } }
再安装上述代码分别为SMUser和SMUserRole创建仓储类,若是须要更复杂的数据库查询操做,能够上上述仓储类中补充实现。
咱们已经知道,DbContext默认支持事务,当实例化一个新的DbContext对象时,就会建立一个新的事务,当调用SaveChanges方法时,事务会提交。问题是,若是咱们使用相同的DbContext对象把多个代码模块的操做放到一个单独的事务中,该怎么办呢?答案就是工做单元(Unit of Work)。
工做单元本质是一个类,它能够在一个事务中跟踪全部的操做,而后将全部的操做做为原子单元执行。看一下仓储类,能够看到DbContext对象是从外面传给它们的。此外,全部的仓储类都没有调用SaveChanges方法,缘由在于,咱们在建立工做单元时会将DbContext对象传给每一个仓储。当想保存修改时,就能够在工做单元上调用SaveChanges方法,也就在DbContext类上调用了SaveChanges方法。这样就会使得涉及多个仓储的全部操做成为单个事务的一部分。
这里定义咱们的工做单元类以下:
using SnmiOA.DAL.Repository; using System; namespace SnmiOA.DAL { public class UnitOfWork : IDisposable { private readonly SnmiOAContext _context = null; private SMUserRepository _userRepository = null; private SMUserRoleRepository _userRoleRepository = null; private RoleRepository _roleRepository = null; public UnitOfWork(SnmiOAContext context) { _context = context; } public SMUserRepository SMUserRepository { get { return _userRepository ?? (_userRepository = new SMUserRepository(_context)); } } public SMUserRoleRepository SMUserRoleRepository { get { return _userRoleRepository ?? (_userRoleRepository = new SMUserRoleRepository(_context)); } } public RoleRepository RoleRepository { get { return _roleRepository ?? (_roleRepository = new RoleRepository(_context)); } } public void SaveChanges() { _context.SaveChanges(); } public void Dispose() { throw new NotImplementedException(); } } }
完