asp.net core 实战项目(一)——ef core的使用

本文为转载,原文:asp.net core 实战项目(一)——ef core的使用

数据库设计

数据结构图如下:



此次实例比较简单,暂时只设计到上述3张表

SMUser:用于存储用户信息。
Role:用于存储角色信息。
SMUser_Role:用建立用户和角色关系的一直关联表。

创建项目

开发工具:visual studio 2015
打开vs2015->新建项目->.NET Core->ASP.NET Core Application(.Net core)
如下图:



给自己的项目取个名字,选个路径,就完事了。
然后在自己创建的解决方案里再新增个类库项目,此类库项目用于实现数据库的交互,也是实现EF Core的地方,如下图:



我创建的项目结构如下图所示:

之后便是引用的添加了:
App项目引用DAL

DAL项目使用Nuget添加以下引用:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

DAL实现

Entities

在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:

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

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; }
    }
}

DbContext实现

在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建立仓储类,如果需要更复杂的数据库查询操作,可以上上述仓储类中补充实现。

UnitOfWork实现

我们已经知道,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();
        }
    }
}

本文为原创,转载请注明出处

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容