开发环境:VS2017、.Net core 2.1、SQLServer数据库
首先,先将项目的基础框架搭建起来,项目使用的是Core EF DBFirst机制,DDD模式
本章实现一下项目框架的基础搭建
1、使用 VS2017创建一个 .net core 的webapi项目,项目创建完成后,在项目中添加相关的业务类库,类库都为.net core 类库
NetCore.App:数据业务层
NetCore.Infrastructure:通用方法
NetCore.Repository:Model实体以及数据库
NetCore.WebApi:webapi 接口
2、NetCore.Repository的搭建
Nuget添加 Microsoft.EntityFrameworkCore.SqlServer、Z.EntityFramework.Plus.EFCore两个包的引用
Common:通用实体类
Domain:数据库表实体类
RequestEntity:WebApi请求参数实体类
ResponseEntity:WebApi返回数据实体类
NetCoreDbContext:数据库上下文
BaseRepository:数据库操作通用方法
UnitWork:数据库事务操作方法
NetCoreDbContext代码
using System;
using Microsoft.EntityFrameworkCore;
using NetCore.Repository.Domain;
namespace NetCore.Repository
{
public class NetCoreDbContext:DbContext
{
public NetCoreDbContext(DbContextOptions options):base(options)
{
}
#region dbSet
public virtual DbSet UserInfos { get; set; }
#endregion
}
}
BaseRepository代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using NetCore.Repository.Domain;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;
namespace NetCore.Repository
{
///
/// 数据操作通用方法
///
///
public class BaseRepository where T : BaseModel
{
protected NetCoreDbContext netCoreDbContext;
public BaseRepository(NetCoreDbContext _netCoreDbContext)
{
netCoreDbContext = _netCoreDbContext;
}
///
/// 新增
///
///
///
public bool Add(T entity)
{
try
{
//netCoreDbContext.Set().Add(entity);
//netCoreDbContext.SaveChanges();
//netCoreDbContext.Entry(entity).State = EntityState.Detached;
netCoreDbContext.Entry(entity).State = EntityState.Added;
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch(Exception ex)
{
return false;
}
}
///
/// 批量添加
///
///
///
public bool BatchAdd(T[] entities)
{
try
{
netCoreDbContext.Set().AddRange(entities);
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected == entities.Length ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 修改
///
///
///
public bool Update(T entity)
{
try
{
netCoreDbContext.Set().Attach(entity);
netCoreDbContext.Entry(entity).State = EntityState.Modified;
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 根据条件更新数据
/// 如:Update(u =>u.Id==1,u =>new User{Name="ok"});
///
/// The where.
/// The entity.
public bool Update(Expression> where, Expression> entity)
{
try
{
netCoreDbContext.Set().Where(where).Update(entity);
return true;
}
catch (Exception ex)
{
return false;
}
}
///
/// 根据ID获取单个数据
///
///
///
public T GetEntiyByID(Guid id)
{
try
{
Expression> where = x => x.ID.Equals(id);
var modelList = netCoreDbContext.Set().Where(where).AsQueryable().ToList();
return modelList.Any() ? modelList.FirstOrDefault() : null;
}
catch (Exception ex)
{
return null;
}
}
///
/// 根据查询条件获取单个数据
///
///
///
public T GetEntityByWhere(Expression> expression)
{
return netCoreDbContext.Set().FirstOrDefault(expression);
}
///
/// 根据ID删除
///
///
///
public bool Delete(Guid id)
{
var model = GetEntiyByID(id);
if (model != null)
{
try
{
netCoreDbContext.Set().Attach(model);
netCoreDbContext.Entry(model).State = EntityState.Deleted;
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
else
{
return false;
}
}
///
/// 删除
///
///
///
public bool Delete(T entity)
{
try
{
netCoreDbContext.Set().Remove(entity);
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 根据条件删除数据
///
///
public bool Delete(Expression> expression)
{
try
{
netCoreDbContext.Set().Where(expression).Delete();
return true;
}
catch (Exception ex)
{
return false;
}
}
///
/// 判断数据是否存在
///
///
///
public bool IsExist(Expression> expression)
{
return netCoreDbContext.Set().Any(expression);
}
///
/// 获取数据列表
///
/// 排序条件
/// 查询条件
/// 排序方式
///
public List GetList(Expression> orderExp,Expression> expression = null,string orderBy="desc")
{
try
{
IQueryable quary;
if (expression == null)
{
quary= netCoreDbContext.Set().AsNoTracking().AsQueryable();
}
else
{
quary= netCoreDbContext.Set().AsNoTracking().AsQueryable().Where(expression);
}
return orderBy == "desc" ? quary.OrderByDescending(orderExp).ToList() : quary.OrderBy(orderExp).ToList();
}
catch (Exception ex)
{
return null;
}
}
///
/// 获取分页数据列表
///
/// 查询条件
/// 每页条数
/// 页码
/// 排序条件
/// 排序方式
///
///
public List GetPageList(Expression> expression,int pageSize,int pageIndex,out int totalCount, Expression> orderExp, string orderBy = "desc")
{
try
{
if (pageIndex < 1)
{
pageIndex = 1;
}
int skipCount = (pageIndex - 1) * pageSize;
totalCount = netCoreDbContext.Set().Where(expression).Count();
IQueryable quary = netCoreDbContext.Set().AsNoTracking().AsQueryable().Where(expression);
return orderBy == "desc" ? quary.OrderByDescending(orderExp).Skip(skipCount).Take(pageSize).ToList() : quary.OrderBy(orderExp).Skip(skipCount).Take(pageSize).ToList();
}
catch (Exception ex)
{
totalCount = 0;
return null;
}
}
}
}
UnitWrok代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using NetCore.Repository.Domain;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;
namespace NetCore.Repository
{
///
/// 数据库事务操作方法
///
public class UnitWork
{
protected NetCoreDbContext netCoreDbContext;
public UnitWork(NetCoreDbContext _netCoreDbContext)
{
netCoreDbContext = _netCoreDbContext;
}
///
/// 新增
///
///
///
public bool Add(T entity) where T:BaseModel
{
try
{
//netCoreDbContext.Set().Add(entity);
//netCoreDbContext.SaveChanges();
//netCoreDbContext.Entry(entity).State = EntityState.Detached;
netCoreDbContext.Entry(entity).State = EntityState.Added;
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 批量添加
///
///
///
public bool BatchAdd(T[] entities) where T:BaseModel
{
try
{
netCoreDbContext.Set().AddRange(entities);
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected == entities.Length ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 修改
///
///
///
public bool Update(T entity) where T:class
{
try
{
netCoreDbContext.Set().Attach(entity);
netCoreDbContext.Entry(entity).State = EntityState.Modified;
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 根据条件更新数据
/// 如:Update(u =>u.Id==1,u =>new User{Name="ok"});
///
/// The where.
/// The entity.
public bool Update(Expression> where, Expression> entity)where T:class
{
try
{
netCoreDbContext.Set().Where(where).Update(entity);
return true;
}
catch (Exception ex)
{
return false;
}
}
///
/// 根据ID获取单个数据
///
///
///
public T GetEntiyByID(Guid id) where T:BaseModel
{
try
{
Expression> where = x => x.ID.Equals(id);
var modelList = netCoreDbContext.Set().Where(where).AsQueryable().ToList();
return modelList.Any() ? modelList.FirstOrDefault() : null;
}
catch (Exception ex)
{
return null;
}
}
///
/// 根据查询条件获取单个数据
///
///
///
public T GetEntityByWhere(Expression> expression) where T:class
{
return netCoreDbContext.Set().FirstOrDefault(expression);
}
///
/// 删除
///
///
///
public bool Delete(T entity) where T:class
{
try
{
netCoreDbContext.Set().Remove(entity);
int rowsAffected = netCoreDbContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
///
/// 根据条件删除数据
///
///
public bool Delete(Expression> expression) where T:class
{
try
{
netCoreDbContext.Set().Where(expression).Delete();
return true;
}
catch (Exception ex)
{
return false;
}
}
///
/// 判断数据是否存在
///
///
///
public bool IsExist(Expression> expression) where T:class
{
return netCoreDbContext.Set().Any(expression);
}
///
/// 获取数据列表
///
/// 排序条件
/// 查询条件
/// 排序方式
///
public List GetList(Expression> orderExp,Expression> expression = null,string orderBy="desc") where T:class
{
try
{
IQueryable quary;
if (expression == null)
{
quary = netCoreDbContext.Set().AsNoTracking().AsQueryable();
}
else
{
quary= netCoreDbContext.Set().AsNoTracking().AsQueryable().Where(expression);
}
return orderBy == "desc"?quary.OrderByDescending(orderExp).ToList():quary.OrderBy(orderExp).ToList();
}
catch (Exception ex)
{
return null;
}
}
///
/// 获取分页数据列表
///
/// 查询条件
/// 每页条数
/// 页码
/// 排序条件
/// 排序方式
///
///
public List GetPageList(Expression> expression, int pageSize, int pageIndex, out int totalCount, Expression> orderExp, string orderBy = "desc") where T:class
{
try
{
if (pageIndex < 1)
{
pageIndex = 1;
}
int skipCount = (pageIndex - 1) * pageSize;
totalCount = netCoreDbContext.Set().Where(expression).Count();
IQueryable quary = netCoreDbContext.Set().AsNoTracking().AsQueryable().Where(expression);
return orderBy == "desc" ? quary.OrderByDescending(orderExp).Skip(skipCount).Take(pageSize).ToList() : quary.OrderBy(orderExp).Skip(skipCount).Take(pageSize).ToList();
}
catch (Exception ex)
{
totalCount = 0;
return null;
}
}
}
}
在Domain下添加BaseModel和UserInfo实体类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace NetCore.Repository.Domain
{
///
/// 通用字段实体类
///
public abstract class BaseModel
{
///
/// 主键
///
[Key]
public string ID { get; set; } = Guid.NewGuid().ToString();
///
/// 创建人
///
[Required,StringLength(50)]
public string CreateUser { get; set; }
///
/// 创建时间
///
public DateTime CreateTime { get; set; } = DateTime.Now;
///
/// 修改人
///
public string ModifyUser { get; set; }
///
/// 修改日期
///
public DateTime? ModifyTime { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace NetCore.Repository.Domain
{
///
/// 用户信息表
///
[Table("UserInfo")]
public class UserInfo:BaseModel
{
///
/// 用户名
///
public string UserName { get; set; }
///
/// 登录名
///
public string LoginAccount { get; set; }
///
/// 登录密码
///
public string LoginPassword { get; set; }
}
}
在WebApi中的appsettings中配置数据库连接,添加ConnectionStrings
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"NetCoreDBContext": "Data Source=.;Initial Catalog=NetCoreWebApi;User=sa;Password=123456"
}
}
在WebApi的Startup.cs中的ConfigureServices设置数据库的连接
services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("NetCoreDBContext")));//获取数据库连接
3、NetCore.App的搭建
项目添加对NetCore.Repository及NetCore.Infrastructure两个项目的引用
在项目中添加BaseApp、UserInfoApp两个业务操作类
using System;
using System.Collections.Generic;
using System.Text;
using NetCore.Repository;
using NetCore.Repository.Domain;
namespace NetCore.App
{
public class BaseApp where T:BaseModel
{
protected UnitWork unitWork;
protected BaseRepository baseRepository;
public BaseApp(UnitWork _unitWork, BaseRepository _baseRepository)
{
unitWork = _unitWork;
baseRepository = _baseRepository;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;
using NetCore.Repository;
using NetCore.Repository.Domain;
using NetCore.Repository.RequestEntity;
using NetCore.Infrastructure;
namespace NetCore.App
{
///
/// 用户信息
///
public class UserInfoApp:BaseApp
{
public UserInfoApp(UnitWork unitWork,BaseRepository baseRepository):base(unitWork,baseRepository)
{
}
///
/// 新增
///
///
///
public bool Add(UserInfo userInfo)
{
return baseRepository.Add(userInfo);
}
///
/// 判断账户是否已存在
///
///
///
///
public bool IsExist(string loginAccount,string id)
{
return baseRepository.IsExist(x => x.LoginAccount.Equals(loginAccount) && !x.ID.Equals(id));
}
///
/// 登录
///
/// 登录名
/// 登录密码
///
public UserInfo Login(string loginAccount,string password)
{
return baseRepository.GetEntityByWhere(x=>x.LoginAccount.Equals(loginAccount)&&x.LoginPassword.Equals(password));
}
///
/// 获取用户信息
///
///
///
public List GetList( UserInfoRequest userInfoRequest)
{
Expression> predicte=x=>true;//查询条件
if (!string.IsNullOrEmpty(userInfoRequest.UserName))
{
predicte = predicte.And(x=>x.UserName.Contains(userInfoRequest.UserName));
}
Expression> predicteSort = x =>x.CreateTime;//排序字段
return baseRepository.GetList(predicteSort, predicte);
}
}
}
RequestEntity添加用户查询条件的实体
using System;
using System.Collections.Generic;
using System.Text;
namespace NetCore.Repository.RequestEntity
{
///
/// 用户查询信息
///
public class UserInfoRequest
{
///
/// 用户名
///
public string UserName { get; set; }
///
/// 登录名
///
public string LoginAccount { get; set; }
///
/// 登录密码
///
public string LoginPassword { get; set; }
}
}
完整代码下载地址:https://download.csdn.net/download/liwan09/11717224