一.首先搭建一个项目
如下图:
Web是ASP.NET Core Web,其他都是用.NET Core
二.创建实体类AdminInfo或是别的内容自拟
三.给实体层的项目添加三个引用包
在vs界面顶端找到“视图”再点击“其他窗口”最后找到“程序包管理控制台”
在默认项目那选择JiaHua.Model
再依次输入:
Install-Package Microsoft.EntityFrameworkCore.SqlServer -version 2.1.1
Install-Package Microsoft.EntityFrameworkCore.Tools -version 2.1.1
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
四.生成数据库
在JiaHua.Model创建一个MaeketContext类
内容如下:
public class MaeketContext : DbContext
{
public DbSet AdminInfo { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optinosBuilder)
{
optinosBuilder.UseSqlServer(@"server=PC-
20190228DYDQ\SQLEXPRESS;database=Market;uid=sa;pwd=sa;");
}
}
把JiaHua.Model设为启动项
再在“程序包管理控制台”输入:Add-Migration build125
生成迁移文件 结果如下:
再在“程序包管理控制台”输入:Update-Database
在SQL Servier生成数据库
五.在JiaHua.Repository中添内容
首先引用包右键点击“依赖项”找到“管理NuGet程序包”
浏览搜索 System.Linq.Dynamic.Core 找到并下载
然后添加类
IRepository类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace JiaHua.Repository
{
///
/// 定义泛型仓储接口
///
/// 实体类型
public interface IRepository where T : class
{
#region 同步
///
/// 判断记录是否存在
///
/// lambda表达式条件
///
bool IsExist(Expression> predicate);
///
/// 新增实体
///
/// 实体
/// 是否立即执行保存
///
bool Add(T entity, bool autoSave = true);
///
/// 批量添加
///
/// 实体列表
/// 是否立即执行保存
///
bool AddRange(IEnumerable entities, bool autoSave = true);
///
/// 更新实体
///
/// 实体
/// 是否立即执行保存
bool Update(T entity, bool autoSave = true);
///
/// 更新部分属性
///
/// 实体
/// 是否立即执行保存
/// 要更新的字段
///
bool Update(T entity, bool autoSave = true, params Expression>[] updatedProperties);
///
/// 更新实体部分属性,泛型方法
///
/// 实体
/// 是否立即执行保存
/// 要更新的字段
///
bool Update(Entity entity, bool autoSave = true, params Expression>[] updatedProperties) where Entity : class;
///
/// 批量更新实体
///
/// 实体列表
/// 是否立即执行保存
bool UpdateRange(IEnumerable entities, bool autoSave = true);
///
/// 删除实体
///
/// 要删除的实体
/// 是否立即执行保存
bool Delete(T entity, bool autoSave = true);
///
/// 批量删除
///
/// 对象集合
///
bool Delete(IEnumerable entities);
///
/// 批量删除
///
/// 对象集合
/// 是否立即执行保存
///
bool Delete(IEnumerable entities, bool autoSave = true);
///
/// 获取实体集合
///
///
IQueryable GetList();
///
/// 根据lambda表达式条件获取实体集合
///
/// 前几条
/// 查询条件
/// 排序
/// 条件参数
///
IQueryable GetList(int top, string predicate, string ordering, params object[] args);
///
/// 根据lambda表达式条件获取实体集合
///
/// lambda表达式条件
///
IQueryable GetList(Expression> predicat);
///
/// 根据lambda表达式条件获取单个实体
///
/// lambda表达式条件
///
T GetModel(Expression> predicate);
///
/// 分页查询
///
/// 当前页
/// 页大小
/// 条件
/// 排序
/// 条件参数
///
IQueryable GetPagedList(int pageIndex, int pageSize, string predicate, string ordering, params object[] args);
///
/// 获取记录总数
///
/// 查询条件
/// 条件参数
///
int GetRecordCount(string predicate, params object[] args);
///
/// 保存
///
int Save();
#endregion
}
}
SyDbContext类:
using JiaHua.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace JiaHua.Repository.Repository
{
public class SyDbContext : DbContext
{
public DbSet AdminInfo { get; set; }
public SyDbContext(DbContextOptions optinosBuilder) : base(optinosBuilder)
{
}
}
}
RepositoryBase类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Linq.Dynamic.Core;
using JiaHua.Repository.Repository;
namespace JiaHua.Repository
{
///
/// 仓储基类
///
/// 实体类型
public abstract class RepositoryBase : IRepository where T : class
{
//定义数据访问上下文对象
protected readonly SyDbContext _dbContext;
///
/// 通过构造函数注入得到数据上下文对象实例
///
///
public RepositoryBase(SyDbContext dbContext)
{
_dbContext = dbContext;
}
#region 同步
///
/// 判断记录是否存在
///
/// lambda表达式条件
///
public bool IsExist(Expression> predicate)
{
return _dbContext.Set().Any(predicate);
}
///
/// 新增实体
///
/// 实体
/// 是否立即执行保存
///
public bool Add(T entity, bool autoSave = true)
{
int row = 0;
_dbContext.Set().Add(entity);
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 批量添加
///
/// 实体列表
/// 是否立即执行保存
///
public bool AddRange(IEnumerable entities, bool autoSave = true)
{
int row = 0;
_dbContext.Set().AddRange(entities);
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 更新实体
///
/// 实体
/// 是否立即执行保存
public bool Update(T entity, bool autoSave = true)
{
int row = 0;
_dbContext.Update(entity);
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 更新实体部分属性
///
/// 实体
/// 是否立即执行保存
/// 要更新的字段
///
public bool Update(T entity, bool autoSave = true, params Expression>[] updatedProperties)
{
int row = 0;
//告诉EF Core开始跟踪实体的更改,
//因为调用DbContext.Attach方法后,EF Core会将实体的State值
//更改回EntityState.Unchanged,
_dbContext.Attach(entity);
if (updatedProperties.Any())
{
foreach (var property in updatedProperties)
{
//告诉EF Core实体的属性已经更改。将属性的IsModified设置为true后,
//也会将实体的State值更改为EntityState.Modified,
//这样就保证了下面SaveChanges的时候会将实体的属性值Update到数据库中。
_dbContext.Entry(entity).Property(property).IsModified = true;
}
}
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 更新实体部分属性,泛型方法
///
/// 实体
/// 是否立即执行保存
/// 要更新的字段
///
public bool Update(Entity entity, bool autoSave = true, params Expression>[] updatedProperties) where Entity : class
{
int row = 0;
//告诉EF Core开始跟踪实体的更改,
//因为调用DbContext.Attach方法后,EF Core会将实体的State值
//更改回EntityState.Unchanged,
_dbContext.Attach(entity);
if (updatedProperties.Any())
{
foreach (var property in updatedProperties)
{
//告诉EF Core实体的属性已经更改。将属性的IsModified设置为true后,
//也会将实体的State值更改为EntityState.Modified,
//这样就保证了下面SaveChanges的时候会将实体的属性值Update到数据库中。
_dbContext.Entry(entity).Property(property).IsModified = true;
}
}
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 批量更新实体
///
/// 实体列表
/// 是否立即执行保存
public bool UpdateRange(IEnumerable entities, bool autoSave = true)
{
int row = 0;
_dbContext.UpdateRange(entities);
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 根据lambda表达式条件获取单个实体
///
/// lambda表达式条件
///
public T GetModel(Expression> predicate)
{
return _dbContext.Set().FirstOrDefault(predicate);
}
///
/// 删除实体
///
/// 要删除的实体
/// 是否立即执行保存
public bool Delete(T entity, bool autoSave = true)
{
int row = 0;
_dbContext.Set().Remove(entity);
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 批量删除
///
/// 对象集合
///
public bool Delete(IEnumerable entities)
{
_dbContext.Set().RemoveRange(entities);
int row = _dbContext.SaveChanges();
return (row > 0);
}
///
/// 批量删除
///
/// 对象集合
/// 是否立即执行保存
///
public bool Delete(IEnumerable entities, bool autoSave = true)
{
int row = 0;
_dbContext.Set().RemoveRange(entities);
if (autoSave)
row = Save();
return (row > 0);
}
///
/// 获取实体集合
///
///
public virtual IQueryable GetList()
{
return _dbContext.Set().AsQueryable();
}
///
/// 根据lambda表达式条件获取单个实体
///
/// lambda表达式条件
///
public virtual IQueryable GetList(Expression> predicate)
{
return _dbContext.Set().Where(predicate);
}
///
/// 根据lambda表达式条件获取实体集合
///
/// 前几条
/// 查询条件
/// 排序
/// 条件参数
///
public virtual IQueryable GetList(int top, string predicate, string ordering, params object[] args)
{
var result = _dbContext.Set().AsQueryable();
if (!string.IsNullOrWhiteSpace(predicate))
result = result.Where(predicate, args);
if (!string.IsNullOrWhiteSpace(ordering))
result = result.OrderBy(ordering);
if (top > 0)
{
result = result.Take(top);
}
return result;
}
///
/// 分页查询,返回实体对象
///
/// 当前页
/// 页大小
/// 条件
/// 排序
/// 条件参数
///
public virtual IQueryable GetPagedList(int pageIndex, int pageSize, string predicate, string ordering, params object[] args)
{
var result = (from p in _dbContext.Set()
select p).AsQueryable();
if (!string.IsNullOrWhiteSpace(predicate))
result = result.Where(predicate, args);
if (!string.IsNullOrWhiteSpace(ordering))
result = result.OrderBy(ordering);
return result.Skip((pageIndex - 1) * pageSize).Take(pageSize);
}
///
/// 获取记录总数
///
/// 查询条件
/// 条件参数
///
public virtual int GetRecordCount(string predicate, params object[] args)
{
if (string.IsNullOrWhiteSpace(predicate))
{
return _dbContext.Set().Count();
}
else
{
return _dbContext.Set().Where(predicate, args).Count();
}
}
///
/// 事务性保存
///
public int Save()
{
int result = _dbContext.SaveChanges();
return result;
}
#endregion
}
}
六.在JiaHua.Web中添加内容
把appsetting.json文件修改为:
{
"ConnectionStrings": {
"ConnectionString": "server=localhost;database=Market;uid=sa;pwd=123456;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
再把Program.cs文件中的CreateWebHostBuilder方法替换
如下:
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
//获取配置
var configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json")//读取配置文件,获取启动的端口号
.Build();
//返回
return WebHost.CreateDefaultBuilder(args)
.UseConfiguration(configuration)
.UseStartup();
}
然后修改Startup.cs的ConfigureServices在方法内添加内容
如下:
public void ConfigureServices(IServiceCollection services)
{
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//依赖注入,取得DbContext实例 使用DbContext池,提高性能
services.AddDbContextPool(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
//数据服务注入
services.AddDataService();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
services.AddDataService();的AddDataService方法后面会提到
七.在JiaHua.service添加类
IUserInfoService类:
public interface IUserInfoService
{
}
UserInfoService类:
public class UserInfoService : IUserInfoService
{
}
八.在JiaHua.Infrastructure中添加内容
首先引用包右键点击“依赖项”找到“管理NuGet程序包”
浏览搜索 Microsoft.Extensions.DependencyInjection 找到并下载
版本要2.1.0的
DataServiceExtension类:
using JiaHua.service;
using JiaHua.service.Service;
using Microsoft.Extensions.DependencyInjection;
namespace JiaHua.Infrastructure
{
public static class DataServiceExtension
{
///
/// 注入数据
///
///
public static IServiceCollection AddDataService(this IServiceCollection services)
{
#region 依赖注入
services.AddScoped();
#endregion
return services;
}
}
}
MD5Encrypt类:
public class MD5Encrypt
{
///
///
///
///
///
public static string Encrypt(string source)
{
if (string.IsNullOrEmpty(source)) return string.Empty;
HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
byte[] bytes = Encoding.UTF8.GetBytes(source);//这里需要区别编码的
byte[] hashValue = provider.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++)
{
sb.Append(hashValue[i].ToString("x2"));
}
return sb.ToString();
}
}
EnumExtension类:
namespace JiaHua.Infrastructure
{
///
/// 枚举扩展属性
///
public static class EnumExtension
{
private static Dictionary> enumCache;
private static Dictionary> EnumCache
{
get
{
if (enumCache == null)
{
enumCache = new Dictionary>();
}
return enumCache;
}
set { enumCache = value; }
}
///
/// 获得枚举提示文本
///
///
///
public static string GetEnumText(this Enum en)
{
string enString = string.Empty;
if (null == en) return enString;
var type = en.GetType();
enString = en.ToString();
if (!EnumCache.ContainsKey(type.FullName))
{
var fields = type.GetFields();
Dictionary temp = new Dictionary();
foreach (var item in fields)
{
var attrs = item.GetCustomAttributes(typeof(TextAttribute), false);
if (attrs.Length == 1)
{
var v = ((TextAttribute)attrs[0]).Value;
temp.Add(item.Name, v);
}
}
EnumCache.Add(type.FullName, temp);
}
if (EnumCache[type.FullName].ContainsKey(enString))
{
return EnumCache[type.FullName][enString];
}
return enString;
}
}
public class TextAttribute : Attribute
{
public TextAttribute(string value)
{
Value = value;
}
public string Value { get; set; }
}
}
九.在JiaHua.UiewModel添加内容
首先右键点击“依赖项”找到“添加引用”
在“项目”中勾选JiaHua.Infrastructure的引用再添加ResponseEnum类
using System;
using System.Collections.Generic;
using System.Text;
using JiaHua.Infrastructure;
namespace JiaHua.Components
{
public enum ResponseEnum
{
///
/// 请求(或处理)成功
///
[Text("请求(或处理)成功")]
Status = 200, //请求(或处理)成功
///
/// 内部请求出错
///
[Text("内部请求出错")]
Error = 500, //内部请求出错
///
/// 未授权标识
///
[Text("未授权标识")]
Unauthorized = 401,//未授权标识
///
/// 请求参数不完整或不正确
///
[Text("请求参数不完整或不正确")]
ParameterError = 400,//请求参数不完整或不正确
///
/// 请求TOKEN失效
///
[Text("请求TOKEN失效")]
TokenInvalid = 403,//请求TOKEN失效
///
/// HTTP请求类型不合法
///
[Text("HTTP请求类型不合法")]
HttpMehtodError = 405,//HTTP请求类型不合法
///
/// HTTP请求不合法,请求参数可能被篡改
///
[Text("HTTP请求不合法,请求参数可能被篡改")]
HttpRequestError = 406,//HTTP请求不合法
///
/// 该URL已经失效
///
[Text("该URL已经失效")]
URLExpireError = 407,//HTTP请求不合法
}
}
再右键点击“依赖项”找到“管理NuGet程序包”
浏览搜索 Newtonsoft.Json 找到并下载
然后添加ResponseResult类
namespace JiaHua.UiewModel
{
///
/// 请求返回统一格式
///
public class ResponseResult
{
///
/// 构造函数
///
public ResponseResult()
{
}
///
/// 构造函数
///
/// 是否成功
/// 状态码
/// 数据
/// 总记录数
public ResponseResult(bool success, string msg, int code, dynamic list, int recordCount)
{
this.success = success;
this.msg = msg;
this.code = code;
this.data = list;
this.count = recordCount;
}
///
/// 构造函数,成功返回列表
///
/// 数据
/// 总记录数
public ResponseResult(dynamic list, int recordCount)
{
this.success = true;
this.data = list;
this.count = recordCount;
}
///
/// 构造函数,操作是否成功
///
/// 数据
/// 状态码
/// 总记录数
public ResponseResult(bool success, int code, string msg)
{
this.success = success;
this.code = code;
this.msg = msg;
}
///
/// 构造函数,操作是否成功
///
/// 数据
/// 总记录数
public ResponseResult(bool success, string msg)
{
this.success = success;
if (success)
{
this.code = 200;
}
else
{
this.code = 500;
}
this.msg = msg;
}
///
/// 是否成功
///
public bool success { get; set; } = true;
///
/// 状态码
///
public int code { set; get; } = 0;
///
/// 总记录数
///
public int count { set; get; } = 0;
///
/// 数据
///
public dynamic data { set; get; }
///
/// 返回信息
///
public string msg { set; get; }
///
/// 序列化为字符串
///
///
public override string ToString()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
}
}
十.最后在JiaHuan.Web的Startup.cs文件中添加内容
public void ConfigureServices(IServiceCollection services)
{
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//依赖注入,取得DbContext实例 使用DbContext池,提高性能
services.AddDbContextPool(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
//数据服务注入
services.AddDataService();
// 注册MVC到Container
services.AddMvc();//这一句
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}