一、環境準備
VS2017 、.net core 2.1
二、功能實現
1、創建.net core 項目
2、項目中創建數據model實體類庫(.net core 類庫),創建完成後,從Nuget搜索安裝Npgsql.EntityFrameworkCore.PostgreSQL
3、創建數據庫上下文 Dbcontext
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Bosch.Rtns.Repository.Domain;
namespace Bosch.Rtns.Repository
{
public class BoschRtnsDBContext:DbContext
{
public BoschRtnsDBContext(DbContextOptions<BoschRtnsDBContext> options) : base(options)
{
}
#region dbSet
public virtual DbSet<OnlineUsers> OnlineUsers { get; set; }
public virtual DbSet<EquipmentFault> EquipmentFault { get; set; }
public virtual DbSet<AppClass> AppClass { get; set; }
public virtual DbSet<RingstoneSetting> RingstoneSetting { get; set; }
public virtual DbSet<FaultLevel> FaultLevel { get; set; }
public virtual DbSet<FaultSolution> FaultSolution { get; set; }
public virtual DbSet<SolutionAttachFiles> SolutionAttachFiles { get; set; }
public virtual DbSet<SolutionComment> SolutionComment { get; set; }
#endregion
}
}
4、封裝數據庫通用方法類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Bosch.Rtns.Repository.Interface
{
public interface IRepository<T> where T : class
{
/// <summary>
/// 新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
bool Add(T entity);
/// <summary>
/// 批量添加
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
bool BatchAdd(T[] entities);
/// <summary>
/// 修改
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
bool Update(T entity);
/// <summary>
/// 根據ID獲取單個數據
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T GetEntiyByID(string id);
/// <summary>
/// 根據查詢條件獲取單個數據
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
T GetEntityByWhere(Expression<Func<T, bool>> expression);
/// <summary>
/// 根據ID刪除
/// </summary>
/// <param name="id"></param>
/// <param name="IsDelete">是否刪除</param>
/// <returns></returns>
bool Delete(string id, bool IsDelete = false);
/// <summary>
/// 刪除
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
bool Delete(T entity);
/// <summary>
/// 判斷數據是否存在
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
bool IsExist(Expression<Func<T, bool>> expression);
/// <summary>
/// 獲取數據列表
/// </summary>
/// <param name="orderExp">排序條件</param>
/// <param name="expression">查詢條件</param>
/// <param name="orderBy">排序方式</param>
/// <returns></returns>
List<T> GetList(Expression<Func<T, dynamic>> orderExp, Expression<Func<T, bool>> expression = null, string orderBy = "desc");
/// <summary>
/// 獲取數據列表
/// </summary>
/// <param name="expression">查詢條件</param>
/// <returns></returns>
List<T> GetList(Expression<Func<T, bool>> expression);
/// <summary>
/// 獲取分頁數據列表
/// </summary>
/// <param name="expression">查詢條件</param>
/// <param name="pageSize">每頁條數</param>
/// <param name="pageIndex">頁碼</param>
/// <param name="orderExp">排序條件</param>
/// <param name="orderBy">排序方式</param>
/// <param name=""></param>
/// <returns></returns>
List<T> GetPageList(Expression<Func<T, bool>> expression, int pageSize, int pageIndex, out int totalCount, Expression<Func<T, dynamic>> orderExp, string orderBy = "desc");
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Bosch.Rtns.Repository.Domain;
using Bosch.Rtns.Repository.Interface;
using Bosch.Rtns.Infrastructure;
namespace Bosch.Rtns.Repository
{
/// <summary>
/// 數據操作通用方法
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseRepository<T> : IRepository<T> where T :BaseEntity
{
protected BoschRtnsDBContext boschRtnsDBContext;
public BaseRepository(BoschRtnsDBContext _boschRtnsDBContext)
{
boschRtnsDBContext = _boschRtnsDBContext;
}
/// <summary>
/// 新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Add(T entity)
{
try
{
boschRtnsDBContext.Entry(entity).State = EntityState.Added;
int rowsAffected = boschRtnsDBContext.SaveChanges();
boschRtnsDBContext.Entry(entity).State = EntityState.Detached;
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("數據新增失敗:"+ex.Message, GetType());
return false;
}
}
/// <summary>
/// 批量添加
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public bool BatchAdd(T[] entities)
{
try
{
boschRtnsDBContext.Set<T>().AddRange(entities);
int rowsAffected = boschRtnsDBContext.SaveChanges();
return rowsAffected == entities.Length ? true : false;
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("批量添加數據失敗:" + ex.Message, GetType());
return false;
}
}
/// <summary>
/// 修改
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Update(T entity)
{
try
{
boschRtnsDBContext.Set<T>().Attach(entity);
boschRtnsDBContext.Entry(entity).State = EntityState.Modified;
int rowsAffected = boschRtnsDBContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("修改數據失敗:" + ex.Message, GetType());
return false;
}
}
/// <summary>
/// 根據ID獲取單個數據
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T GetEntiyByID(string id)
{
try
{
Expression<Func<T, bool>> where = x => x.Id.Equals(id);
var modelList = boschRtnsDBContext.Set<T>().Where(where).AsQueryable().ToList();
return modelList.Any() ? modelList.FirstOrDefault() : null;
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("根據ID獲取單個數據失敗:" + ex.Message, GetType());
return null;
}
}
/// <summary>
/// 根據查詢條件獲取單個數據
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public T GetEntityByWhere(Expression<Func<T, bool>> expression)
{
try
{
return boschRtnsDBContext.Set<T>().FirstOrDefault(expression);
}
catch(Exception ex)
{
LogNetManager.WriteErrorLog("根據查詢條件獲取單個數據失敗:" + ex.Message, GetType());
return null;
}
}
/// <summary>
/// 根據ID刪除
/// </summary>
/// <param name="id"></param>
/// <param name="IsDelete">是否刪除</param>
/// <returns></returns>
public bool Delete(string id,bool IsDelete=false)
{
var model = GetEntiyByID(id);
if (model != null)
{
try
{
if (IsDelete)
{
boschRtnsDBContext.Set<T>().Attach(model);
boschRtnsDBContext.Entry(model).State = EntityState.Deleted;
int rowsAffected = boschRtnsDBContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
else
{
model.IsDelete = 1;
return Update(model);
}
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("根據ID刪除數據失敗:" + ex.Message, GetType());
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Delete(T entity)
{
try
{
boschRtnsDBContext.Set<T>().Remove(entity);
int rowsAffected = boschRtnsDBContext.SaveChanges();
return rowsAffected > 0 ? true : false;
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("刪除數據失敗:" + ex.Message, GetType());
return false;
}
}
/// <summary>
/// 判斷數據是否存在
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public bool IsExist(Expression<Func<T, bool>> expression)
{
try
{
return boschRtnsDBContext.Set<T>().Any(expression);
}
catch(Exception ex)
{
LogNetManager.WriteErrorLog("判斷數據是否存在失敗:" + ex.Message, GetType());
return true;
}
}
/// <summary>
/// 獲取數據列表
/// </summary>
/// <param name="orderExp">排序條件</param>
/// <param name="expression">查詢條件</param>
/// <param name="orderBy">排序方式</param>
/// <returns></returns>
public List<T> GetList(Expression<Func<T, dynamic>> orderExp, Expression<Func<T, bool>> expression = null, string orderBy = "desc")
{
try
{
IQueryable<T> quary;
if (expression == null)
{
quary = boschRtnsDBContext.Set<T>().AsNoTracking().AsQueryable();
}
else
{
quary = boschRtnsDBContext.Set<T>().AsNoTracking().AsQueryable().Where(expression);
}
return orderBy == "desc" ? quary.OrderByDescending(orderExp).ToList() : quary.OrderBy(orderExp).ToList();
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("獲取數據列表失敗:" + ex.Message, GetType());
return null;
}
}
/// <summary>
/// 獲取數據列表
/// </summary>
/// <param name="expression">查詢條件</param>
/// <returns></returns>
public List<T> GetList( Expression<Func<T, bool>> expression)
{
try
{
IQueryable<T> quary= boschRtnsDBContext.Set<T>().AsNoTracking().AsQueryable().Where(expression);
return quary.ToList();
}
catch (Exception ex)
{
LogNetManager.WriteErrorLog("獲取數據列表失敗:" + ex.Message, GetType());
return null;
}
}
/// <summary>
/// 獲取分頁數據列表
/// </summary>
/// <param name="expression">查詢條件</param>
/// <param name="pageSize">每頁條數</param>
/// <param name="pageIndex">頁碼</param>
/// <param name="orderExp">排序條件</param>
/// <param name="orderBy">排序方式</param>
/// <param name=""></param>
/// <returns></returns>
public List<T> GetPageList(Expression<Func<T, bool>> expression, int pageSize, int pageIndex, out int totalCount, Expression<Func<T, dynamic>> orderExp, string orderBy = "desc")
{
try
{
if (pageIndex < 1)
{
pageIndex = 1;
}
int skipCount = (pageIndex - 1) * pageSize;
totalCount = boschRtnsDBContext.Set<T>().Where(expression).Count();
IQueryable<T> quary = boschRtnsDBContext.Set<T>().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)
{
LogNetManager.WriteErrorLog("獲取分頁數據列表失敗:" + ex.Message, GetType());
totalCount = 0;
return null;
}
}
}
}
5、配置數據庫連接
appsettings中添加數據庫的配置
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"BoschRtnsDBContext": "Server=localhost;Port=5432;Database=boschRtns;User Id=postgres;Password=123456"
}
}
start up ConfigureServices中設置數據庫連接
string dbCoonectionstring = Configuration.GetConnectionString("BoschRtnsDBContext");//獲取數據庫連接
services.AddDbContext<BoschRtnsDBContext>(options => options.UseNpgsql(dbCoonectionstring));//數據庫連接
6、數據業務層調用(示例)
using System;
using Bosch.Rtns.Repository.Interface;
using Bosch.Rtns.Repository.Domain;
namespace Bosch.Rtns.App
{
public class BaseApp<T> where T: BaseEntity
{
protected IUnitWork UnitWork;
protected IRepository<T> Repository;
/// <summary>
///
/// </summary>
/// <param name="unitWork"></param>
/// <param name="repository"></param>
public BaseApp(IUnitWork unitWork, IRepository<T> repository)
{
UnitWork = unitWork;
Repository = repository;
}
/// <summary>
/// 根據id獲取信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T GetEntityByID(string id)
{
return Repository.GetEntiyByID(id);
}
/// <summary>
/// 按id批量刪除
/// </summary>
/// <param name="ids"></param>
public bool DeleteById(string ids)
{
int okCount = 0;
var idArrary = ids.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach(var id in idArrary)
{
var result=Repository.Delete(id);
if (result)
{
okCount++;
}
}
return (okCount == idArrary.Length) ? true : false;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;
using Bosch.Rtns.Repository.Domain;
using Bosch.Rtns.Repository.Request;
using Bosch.Rtns.Repository.Response;
using Bosch.Rtns.Repository.Interface;
using Bosch.Rtns.Infrastructure;
namespace Bosch.Rtns.App
{
/// <summary>
/// 在線用戶業務層
/// </summary>
public class OnlineUsersApp:BaseApp<OnlineUsers>
{
public OnlineUsersApp(IUnitWork unitWork, IRepository<OnlineUsers> repository) : base(unitWork, repository)
{
}
/// <summary>
/// 新增
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Add(OnlineUsers item)
{
item.Id = Guid.NewGuid().ToString();
item.CreateTime = DateTime.Now;
return Repository.Add(item);
}
/// <summary>
/// 修改
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Update(OnlineUsers item)
{
var model = Repository.GetEntiyByID(item.Id);
if (model != null)
{
model.DeviceId = item.DeviceId;
model.DeviceBattery = item.DeviceBattery;
model.LoginName = item.LoginName;
model.IsOnline = item.IsOnline;
model.ModifyTime = DateTime.Now;
}
return Repository.Update(model);
}
/// <summary>
/// 根據設備ID保存數據
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Save(OnlineUsers item)
{
var model = Repository.GetEntityByWhere(x=>x.DeviceId.Equals(item.DeviceId));
if (model == null)
{
item.Id = Guid.NewGuid().ToString();
item.CreateTime = DateTime.Now;
return Repository.Add(item);
}
else
{
model.DeviceId = item.DeviceId;
model.DeviceBattery = item.DeviceBattery;
model.LoginName = item.LoginName;
model.IsOnline = item.IsOnline;
model.ModifyTime = DateTime.Now;
return Repository.Update(model);
}
}
/// <summary>
/// 根據設備id更新用戶在線狀態
/// </summary>
/// <param name="deviceId"></param>
/// <param name="isOnline"></param>
/// <returns></returns>
public bool UpdateByDeviceId(string deviceId,int isOnline)
{
var model = Repository.GetEntityByWhere(x=>x.DeviceId.Equals(deviceId));
if (model != null)
{
model.IsOnline = isOnline;
model.ModifyTime = DateTime.Now;
}
return Repository.Update(model);
}
/// <summary>
/// 獲取分頁數據
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ResponseData GetPageList(OnlineUserSearchRequest request)
{
Expression<Func<OnlineUsers, dynamic>> predicteSort = x => x.CreateTime;//排序字段
Expression<Func<OnlineUsers, bool>> predicate = x =>x.IsDelete==0&&x.IsOnline==1;
if (!string.IsNullOrEmpty(request.LoginName))
{
predicate = predicate.And(x => x.LoginName.Contains(request.LoginName));
}
int total = 0;
var dataList = Repository.GetPageList(predicate,request.PageSize, request.PageIndex,out total, predicteSort);
var result = new ResponseData();
result.DataResult = dataList;
result.TotalCount = total;
if (dataList == null)
{
result.Code = 500;
result.Message = "服務器錯誤";
}
return result;
}
}
}