This commit is contained in:
454313500@qq.com
2021-03-20 21:56:15 +08:00
parent 2e5b991db0
commit 367f8f8830
16 changed files with 240 additions and 50 deletions

View File

@@ -1,4 +1,5 @@
using CC.Yi.IBLL; using CC.Yi.IBLL;
using CC.Yi.Model;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@@ -20,11 +21,50 @@ namespace CC.Yi.API.Controllers
_logger = logger; _logger = logger;
} }
#region
//下面,经典的 增删改查 即为简易--Yi意框架
//注意:请确保你的数据库中存在合理的数据
#endregion
[HttpGet] [HttpGet]
public IActionResult Test() public IActionResult GetTest()//查
{ {
var data = _studentBll.GetAllEntities().ToList(); var data = _studentBll.GetAllEntities().ToList();
return Content(Common.JsonFactory.JsonToString(data)); return Content(Common.JsonFactory.JsonToString(data));
} }
[HttpGet]
public IActionResult AddTest()//增
{
List<student> students = new List<student>() {new student { name = "学生a" } ,new student { name="学生d"} };
_studentBll.Add(students);
return Content("ok");
}
[HttpGet]
public IActionResult RemoveTest()//删
{
if (_studentBll.Delete(u=>u.name=="学生a"))
{
return Content("ok");
}
else
{
return Content("no");
}
}
[HttpGet]
public IActionResult UpdateTest()//改
{
if (_studentBll.Update(new student { id=2, name = "学生a" }, "name"))
{
return Content("ok");
}
else
{
return Content("no");
}
}
} }
} }

View File

@@ -0,0 +1,40 @@
// <auto-generated />
using CC.Yi.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CC.Yi.API.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20210320082935_yi2")]
partial class yi2
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.4")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("CC.Yi.Model.student", b =>
{
b.Property<int>("id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("name")
.HasColumnType("nvarchar(max)");
b.HasKey("id");
b.ToTable("student");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace CC.Yi.API.Migrations
{
public partial class yi2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "name",
table: "student",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "name",
table: "student",
type: "int",
nullable: false,
defaultValue: 0,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
}
}
}

View File

@@ -25,8 +25,8 @@ namespace CC.Yi.API.Migrations
.HasColumnType("int") .HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("name") b.Property<string>("name")
.HasColumnType("int"); .HasColumnType("nvarchar(max)");
b.HasKey("id"); b.HasKey("id");

View File

@@ -1,5 +1,7 @@
using CC.Yi.DAL;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@@ -13,7 +15,22 @@ namespace CC.Yi.API
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
CreateHostBuilder(args).Build().Run(); var host = CreateHostBuilder(args).Build();
var scope = host.Services.CreateScope();
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<Model.DataContext>();
DbContentFactory.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
} }
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>

View File

@@ -8,5 +8,5 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStringBySQL": "server=.;Database=cctest;UId=sa;PWD=Qz52013142020.", "ConnectionStringBySQL": "server=.;Database=cctest;UId=sa;PWD=Qz52013142020.",
"ConnectionStringByMySQL": "Data Source=49.235.212.122;Database=GraduationProject;User ID=root;Password=Qz52013142020.;pooling=true;port=3306;sslmode=none;CharSet=utf8;" "ConnectionStringByMySQL": "Data Source=.;Database=cctest;User ID=root;Password=Qz52013142020.;pooling=true;port=3306;sslmode=none;CharSet=utf8;"
} }

View File

@@ -15,6 +15,7 @@ namespace CC.Yi.BLL
{ {
CurrentDal = cd; CurrentDal = cd;
} }
public IQueryable<T> GetAllEntities() public IQueryable<T> GetAllEntities()
{ {
return CurrentDal.GetAllEntities(); return CurrentDal.GetAllEntities();
@@ -49,12 +50,24 @@ namespace CC.Yi.BLL
return entity; return entity;
} }
public bool Add(IEnumerable<T> entities)
{
CurrentDal.AddRange(entities);
return DbSession.SaveChanges() > 0;
}
public bool Update(T entity) public bool Update(T entity)
{ {
CurrentDal.Update(entity); CurrentDal.Update(entity);
return DbSession.SaveChanges() > 0; return DbSession.SaveChanges() > 0;
} }
public bool Update(T entity, params string[] propertyNames)
{
CurrentDal.Update(entity,propertyNames);
return DbSession.SaveChanges() > 0;
}
public bool Delete(T entity) public bool Delete(T entity)
{ {
CurrentDal.Delete(entity); CurrentDal.Delete(entity);
@@ -73,14 +86,24 @@ namespace CC.Yi.BLL
return DbSession.SaveChanges() > 0; return DbSession.SaveChanges() > 0;
} }
public int DeleteList(List<int> ids) public bool Delete(IEnumerable<int> ids)
{ {
foreach (var id in ids) foreach (var id in ids)
{ {
CurrentDal.Detete(id); CurrentDal.Detete(id);
} }
return DbSession.SaveChanges();//这里把SaveChanges方法提到了循环体外自然就与数据库交互一次 return DbSession.SaveChanges()>0;
} }
public bool Delete(Expression<Func<T, bool>> where)
{
IQueryable<T> entities = CurrentDal.GetEntities(where);
if (entities != null)
{
CurrentDal.DeteteRange(entities);
return DbSession.SaveChanges()>0;
}
return false;
}
} }
} }

View File

@@ -1,7 +1,9 @@
using CC.Yi.IDAL; using CC.Yi.IDAL;
using CC.Yi.Model; using CC.Yi.Model;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
@@ -9,10 +11,9 @@ namespace CC.Yi.DAL
{ {
public class BaseDal<T> : IBaseDal<T> where T : class, new() public class BaseDal<T> : IBaseDal<T> where T : class, new()
{ {
public DataContext Db; public DbContext Db
public BaseDal(DataContext _Db)
{ {
Db = _Db; get { return DbContentFactory.GetCurrentDbContent(); }
} }
public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda) public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
{ {
@@ -65,6 +66,11 @@ namespace CC.Yi.DAL
//Db.SaveChanges(); //Db.SaveChanges();
return entity; return entity;
} }
public bool AddRange(IEnumerable<T> entities)
{
Db.Set<T>().AddRange(entities);
return true;
}
public bool Update(T entity) public bool Update(T entity)
{ {
@@ -73,7 +79,16 @@ namespace CC.Yi.DAL
//return Db.SaveChanges() > 0; //return Db.SaveChanges() > 0;
return true; return true;
} }
public bool Update(T entity, params string[] propertyNames)
{
EntityEntry entry = Db.Entry<T>(entity);
entry.State = EntityState.Unchanged;
foreach (var item in propertyNames)
{
entry.Property(item).IsModified = true;
}
return true;
}
public bool Delete(T entity) public bool Delete(T entity)
{ {
@@ -87,6 +102,12 @@ namespace CC.Yi.DAL
Db.Set<T>().Remove(entity);//由于这里先Find找到了实体所以这里可以用Remove标记该实体要移除删除。如果不是先Find到实体就需要用System.Data.Entity.EntityState.Deleted Db.Set<T>().Remove(entity);//由于这里先Find找到了实体所以这里可以用Remove标记该实体要移除删除。如果不是先Find到实体就需要用System.Data.Entity.EntityState.Deleted
return true; return true;
} }
public bool DeteteRange(IEnumerable<T> entity)
{
Db.Set<T>().RemoveRange(entity);
return true;
}
} }
} }

View File

@@ -8,43 +8,36 @@ namespace CC.Yi.DAL
{ {
public class DbContentFactory public class DbContentFactory
{ {
private static DataContext Webcontext; private static DataContext Webcontext;
public static void Initialize(DataContext webContext)
public DbContentFactory(DataContext webContext)
{ {
Webcontext = webContext; Webcontext = webContext;
} }
//public static void Initialize(DataContext webContext)
//{
// Webcontext = webContext;
//}
public static DataContext GetCurrentDbContent() public static DataContext GetCurrentDbContent()
{ {
////return new DataModelContainer(); //return new DataModelContainer();
////一次请求共用一个上下文实例 //一次请求共用一个上下文实例
////每一次http请求都会开启一个新的线程保证在一个线程中,DbContext是唯一的 //每一次http请求都会开启一个新的线程保证在一个线程中,DbContext是唯一的
////CallContext是线程内部唯一的数据槽一块内存空间/容器),相当于一个键值对数据容器通过key获取value了,需要引入System.Runtime.Remoting.Messaging;命名空间 //CallContext是线程内部唯一的数据槽一块内存空间/容器),相当于一个键值对数据容器通过key获取value了,需要引入System.Runtime.Remoting.Messaging;命名空间
//DbContext db = CallContext.GetData("DbContext") as DbContext; DataContext db = CallContext.GetData("DbContext") as DataContext;
////从 CallContext 中检索具有指定key“DbContext”的对象并强转为DbContext //从 CallContext 中检索具有指定key“DbContext”的对象并强转为DbContext
//if (db == null)//线程在数据槽里面没有此上下文 if (db == null)//线程在数据槽里面没有此上下文
//{ {
// db = Webcontext; db = Webcontext;
// CallContext.SetData("DbContext", db);//放到数据槽中去,DbContext是keydb是value CallContext.SetData("DbContext", db);//放到数据槽中去,DbContext是keydb是value
//} }
//return db; return db;
return Webcontext;
} }
//private static class CallContext private static class CallContext
//{ {
// static ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>(); static ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>();
// public static void SetData(string name, object data) => public static void SetData(string name, object data) =>
// state.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data; state.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data;
// public static object GetData(string name) => public static object GetData(string name) =>
// state.TryGetValue(name, out AsyncLocal<object> data) ? data.Value : null; state.TryGetValue(name, out AsyncLocal<object> data) ? data.Value : null;
//} }
} }
} }

View File

@@ -8,8 +8,5 @@ namespace CC.Yi.DAL
{ {
public partial class studentDal : BaseDal<student>, IstudentDal public partial class studentDal : BaseDal<student>, IstudentDal
{ {
public studentDal(DataContext _Db) : base(_Db)
{
}
} }
} }

View File

@@ -25,9 +25,6 @@ namespace CC.Yi.DAL
#> #>
public partial class <#=k #>Dal : BaseDal<<#=k #>>, I<#=k #>Dal public partial class <#=k #>Dal : BaseDal<<#=k #>>, I<#=k #>Dal
{ {
public <#=k #>Dal(DataContext _Db) : base(_Db)
{
}
} }
<# } #> <# } #>
} }

View File

@@ -15,7 +15,7 @@ namespace CC.Yi.DALFactory
IstudentDal Data = CallContext.GetData("studentDal") as IstudentDal; IstudentDal Data = CallContext.GetData("studentDal") as IstudentDal;
if (Data == null) if (Data == null)
{ {
Data = new studentDal(DbSessionFactory.GetCurrentDbSession().GetDbContent()); Data = new studentDal();
CallContext.SetData("studentDal", Data); CallContext.SetData("studentDal", Data);
} }
return Data; return Data;

View File

@@ -32,7 +32,7 @@ namespace CC.Yi.DALFactory
I<#=k #>Dal Data = CallContext.GetData("<#=k #>Dal") as I<#=k #>Dal; I<#=k #>Dal Data = CallContext.GetData("<#=k #>Dal") as I<#=k #>Dal;
if (Data == null) if (Data == null)
{ {
Data = new <#=k #>Dal(DbSessionFactory.GetCurrentDbSession().GetDbContent()); Data = new <#=k #>Dal();
CallContext.SetData("<#=k #>Dal", Data); CallContext.SetData("<#=k #>Dal", Data);
} }
return Data; return Data;

View File

@@ -11,6 +11,7 @@ namespace CC.Yi.IBLL
//得到全部实体 //得到全部实体
#endregion #endregion
IQueryable<T> GetAllEntities(); IQueryable<T> GetAllEntities();
#region #region
//通过表达式得到实体 //通过表达式得到实体
#endregion #endregion
@@ -36,11 +37,21 @@ namespace CC.Yi.IBLL
#endregion #endregion
T Add(T entity); T Add(T entity);
#region
//添加多个实体
#endregion
bool Add(IEnumerable<T> entities);
#region #region
//更新实体 //更新实体
#endregion #endregion
bool Update(T entity); bool Update(T entity);
#region
//更新实体部分属性
#endregion
bool Update(T entity, params string[] propertyNames);
#region #region
//删除实体 //删除实体
#endregion #endregion
@@ -54,6 +65,11 @@ namespace CC.Yi.IBLL
#region #region
//通过id列表删除多个实体 //通过id列表删除多个实体
#endregion #endregion
int DeleteList(List<int> ids); bool Delete(IEnumerable<int> ids);
#region
//通过表达式删除实体
#endregion
bool Delete(Expression<Func<T, bool>> where);
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
@@ -36,11 +37,20 @@ namespace CC.Yi.IDAL
#endregion #endregion
T Add(T entity); T Add(T entity);
#region
//添加多个实体
#endregion
bool AddRange(IEnumerable<T> entities);
#region #region
//更新单个实体 //更新单个实体
#endregion #endregion
bool Update(T entity); bool Update(T entity);
#region
//更新单个实体部分属性
#endregion
bool Update(T entity, params string[] propertyNames);
#region #region
//删除单个实体 //删除单个实体
#endregion #endregion
@@ -50,5 +60,10 @@ namespace CC.Yi.IDAL
//通过id删除实体 //通过id删除实体
#endregion #endregion
bool Detete(int id); bool Detete(int id);
#region
//删除多个实体
#endregion
bool DeteteRange(IEnumerable<T> entity);
} }
} }

View File

@@ -11,6 +11,6 @@ namespace CC.Yi.Model
[Key] [Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; } public int id { get; set; }
public int name { get; set; } public string name { get; set; }
} }
} }