diff --git a/CC.Yi.API/Controllers/StudentController.cs b/CC.Yi.API/Controllers/StudentController.cs index 5411f596..41de2620 100644 --- a/CC.Yi.API/Controllers/StudentController.cs +++ b/CC.Yi.API/Controllers/StudentController.cs @@ -1,4 +1,5 @@ using CC.Yi.IBLL; +using CC.Yi.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; @@ -20,11 +21,50 @@ namespace CC.Yi.API.Controllers _logger = logger; } + + #region + //下面,经典的 增删改查 即为简易--Yi意框架 + //注意:请确保你的数据库中存在合理的数据 + #endregion [HttpGet] - public IActionResult Test() + public IActionResult GetTest()//查 { var data = _studentBll.GetAllEntities().ToList(); return Content(Common.JsonFactory.JsonToString(data)); } + [HttpGet] + public IActionResult AddTest()//增 + { + List students = new List() {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"); + } + + } } } diff --git a/CC.Yi.API/Migrations/20210320082935_yi2.Designer.cs b/CC.Yi.API/Migrations/20210320082935_yi2.Designer.cs new file mode 100644 index 00000000..c9bbf025 --- /dev/null +++ b/CC.Yi.API/Migrations/20210320082935_yi2.Designer.cs @@ -0,0 +1,40 @@ +// +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("id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("name") + .HasColumnType("nvarchar(max)"); + + b.HasKey("id"); + + b.ToTable("student"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/CC.Yi.API/Migrations/20210320082935_yi2.cs b/CC.Yi.API/Migrations/20210320082935_yi2.cs new file mode 100644 index 00000000..6875efa1 --- /dev/null +++ b/CC.Yi.API/Migrations/20210320082935_yi2.cs @@ -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( + name: "name", + table: "student", + type: "nvarchar(max)", + nullable: true, + oldClrType: typeof(int), + oldType: "int"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "name", + table: "student", + type: "int", + nullable: false, + defaultValue: 0, + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + } + } +} diff --git a/CC.Yi.API/Migrations/DataContextModelSnapshot.cs b/CC.Yi.API/Migrations/DataContextModelSnapshot.cs index d2ae13a7..1952adda 100644 --- a/CC.Yi.API/Migrations/DataContextModelSnapshot.cs +++ b/CC.Yi.API/Migrations/DataContextModelSnapshot.cs @@ -25,8 +25,8 @@ namespace CC.Yi.API.Migrations .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - b.Property("name") - .HasColumnType("int"); + b.Property("name") + .HasColumnType("nvarchar(max)"); b.HasKey("id"); diff --git a/CC.Yi.API/Program.cs b/CC.Yi.API/Program.cs index 5457af7a..970c28f8 100644 --- a/CC.Yi.API/Program.cs +++ b/CC.Yi.API/Program.cs @@ -1,5 +1,7 @@ +using CC.Yi.DAL; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; @@ -13,7 +15,22 @@ namespace CC.Yi.API { 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(); + DbContentFactory.Initialize(context); + } + catch (Exception ex) + { + var logger = services.GetRequiredService>(); + logger.LogError(ex, "An error occurred while seeding the database."); + } + } + host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => diff --git a/CC.Yi.API/appsettings.json b/CC.Yi.API/appsettings.json index 8fcd04df..0112e26e 100644 --- a/CC.Yi.API/appsettings.json +++ b/CC.Yi.API/appsettings.json @@ -8,5 +8,5 @@ }, "AllowedHosts": "*", "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;" } diff --git a/CC.Yi.BLL/BaseBll.cs b/CC.Yi.BLL/BaseBll.cs index 5e7a1a4f..908a6b28 100644 --- a/CC.Yi.BLL/BaseBll.cs +++ b/CC.Yi.BLL/BaseBll.cs @@ -15,6 +15,7 @@ namespace CC.Yi.BLL { CurrentDal = cd; } + public IQueryable GetAllEntities() { return CurrentDal.GetAllEntities(); @@ -49,12 +50,24 @@ namespace CC.Yi.BLL return entity; } + public bool Add(IEnumerable entities) + { + CurrentDal.AddRange(entities); + return DbSession.SaveChanges() > 0; + } + public bool Update(T entity) { CurrentDal.Update(entity); 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) { CurrentDal.Delete(entity); @@ -73,14 +86,24 @@ namespace CC.Yi.BLL return DbSession.SaveChanges() > 0; } - public int DeleteList(List ids) + public bool Delete(IEnumerable ids) { foreach (var id in ids) { CurrentDal.Detete(id); } - return DbSession.SaveChanges();//这里把SaveChanges方法提到了循环体外,自然就与数据库交互一次 + return DbSession.SaveChanges()>0; } + public bool Delete(Expression> where) + { + IQueryable entities = CurrentDal.GetEntities(where); + if (entities != null) + { + CurrentDal.DeteteRange(entities); + return DbSession.SaveChanges()>0; + } + return false; + } } } diff --git a/CC.Yi.DAL/BaseDal.cs b/CC.Yi.DAL/BaseDal.cs index 70e00edd..4839e885 100644 --- a/CC.Yi.DAL/BaseDal.cs +++ b/CC.Yi.DAL/BaseDal.cs @@ -1,7 +1,9 @@ using CC.Yi.IDAL; using CC.Yi.Model; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; using System; +using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -9,10 +11,9 @@ namespace CC.Yi.DAL { public class BaseDal : IBaseDal where T : class, new() { - public DataContext Db; - public BaseDal(DataContext _Db) + public DbContext Db { - Db = _Db; + get { return DbContentFactory.GetCurrentDbContent(); } } public IQueryable GetEntities(Expression> whereLambda) { @@ -65,6 +66,11 @@ namespace CC.Yi.DAL //Db.SaveChanges(); return entity; } + public bool AddRange(IEnumerable entities) + { + Db.Set().AddRange(entities); + return true; + } public bool Update(T entity) { @@ -73,7 +79,16 @@ namespace CC.Yi.DAL //return Db.SaveChanges() > 0; return true; } - + public bool Update(T entity, params string[] propertyNames) + { + EntityEntry entry = Db.Entry(entity); + entry.State = EntityState.Unchanged; + foreach (var item in propertyNames) + { + entry.Property(item).IsModified = true; + } + return true; + } public bool Delete(T entity) { @@ -87,6 +102,12 @@ namespace CC.Yi.DAL Db.Set().Remove(entity);//由于这里先Find找到了实体,所以这里可以用Remove标记该实体要移除(删除)。如果不是先Find到实体就需要用System.Data.Entity.EntityState.Deleted return true; } + public bool DeteteRange(IEnumerable entity) + { + Db.Set().RemoveRange(entity); + return true; + } + } } diff --git a/CC.Yi.DAL/DbContentFactory.cs b/CC.Yi.DAL/DbContentFactory.cs index a89b3cb8..9ca47789 100644 --- a/CC.Yi.DAL/DbContentFactory.cs +++ b/CC.Yi.DAL/DbContentFactory.cs @@ -8,43 +8,36 @@ namespace CC.Yi.DAL { public class DbContentFactory { - private static DataContext Webcontext; - - public DbContentFactory(DataContext webContext) + private static DataContext Webcontext; + public static void Initialize(DataContext webContext) { Webcontext = webContext; } - - //public static void Initialize(DataContext webContext) - //{ - // Webcontext = webContext; - //} public static DataContext GetCurrentDbContent() { - ////return new DataModelContainer(); - ////一次请求共用一个上下文实例 - ////每一次http请求都会开启一个新的线程,保证在一个线程中,DbContext是唯一的 - ////CallContext:是线程内部唯一的数据槽(一块内存空间/容器),相当于一个键值对数据容器,通过key获取value了,需要引入System.Runtime.Remoting.Messaging;命名空间 - //DbContext db = CallContext.GetData("DbContext") as DbContext; - ////从 CallContext 中检索具有指定key“DbContext”的对象,并强转为DbContext - //if (db == null)//线程在数据槽里面没有此上下文 - //{ - // db = Webcontext; - // CallContext.SetData("DbContext", db);//放到数据槽中去,DbContext是key,db是value - //} - //return db; - return Webcontext; + //return new DataModelContainer(); + //一次请求共用一个上下文实例 + //每一次http请求都会开启一个新的线程,保证在一个线程中,DbContext是唯一的 + //CallContext:是线程内部唯一的数据槽(一块内存空间/容器),相当于一个键值对数据容器,通过key获取value了,需要引入System.Runtime.Remoting.Messaging;命名空间 + DataContext db = CallContext.GetData("DbContext") as DataContext; + //从 CallContext 中检索具有指定key“DbContext”的对象,并强转为DbContext + if (db == null)//线程在数据槽里面没有此上下文 + { + db = Webcontext; + CallContext.SetData("DbContext", db);//放到数据槽中去,DbContext是key,db是value + } + return db; } - //private static class CallContext - //{ - // static ConcurrentDictionary> state = new ConcurrentDictionary>(); + private static class CallContext + { + static ConcurrentDictionary> state = new ConcurrentDictionary>(); - // public static void SetData(string name, object data) => - // state.GetOrAdd(name, _ => new AsyncLocal()).Value = data; + public static void SetData(string name, object data) => + state.GetOrAdd(name, _ => new AsyncLocal()).Value = data; - // public static object GetData(string name) => - // state.TryGetValue(name, out AsyncLocal data) ? data.Value : null; - //} + public static object GetData(string name) => + state.TryGetValue(name, out AsyncLocal data) ? data.Value : null; + } } } diff --git a/CC.Yi.DAL/T4DAL.cs b/CC.Yi.DAL/T4DAL.cs index e4656a91..ad7c9133 100644 --- a/CC.Yi.DAL/T4DAL.cs +++ b/CC.Yi.DAL/T4DAL.cs @@ -8,8 +8,5 @@ namespace CC.Yi.DAL { public partial class studentDal : BaseDal, IstudentDal { - public studentDal(DataContext _Db) : base(_Db) - { - } } } \ No newline at end of file diff --git a/CC.Yi.DAL/T4DAL.tt b/CC.Yi.DAL/T4DAL.tt index bd65067b..618fe8e4 100644 --- a/CC.Yi.DAL/T4DAL.tt +++ b/CC.Yi.DAL/T4DAL.tt @@ -25,9 +25,6 @@ namespace CC.Yi.DAL #> public partial class <#=k #>Dal : BaseDal<<#=k #>>, I<#=k #>Dal { - public <#=k #>Dal(DataContext _Db) : base(_Db) - { - } } <# } #> } \ No newline at end of file diff --git a/CC.Yi.DALFactory/T4StaticDalFactory.cs b/CC.Yi.DALFactory/T4StaticDalFactory.cs index 2733dbb1..9b6f14b9 100644 --- a/CC.Yi.DALFactory/T4StaticDalFactory.cs +++ b/CC.Yi.DALFactory/T4StaticDalFactory.cs @@ -15,7 +15,7 @@ namespace CC.Yi.DALFactory IstudentDal Data = CallContext.GetData("studentDal") as IstudentDal; if (Data == null) { - Data = new studentDal(DbSessionFactory.GetCurrentDbSession().GetDbContent()); + Data = new studentDal(); CallContext.SetData("studentDal", Data); } return Data; diff --git a/CC.Yi.DALFactory/T4StaticDalFactory.tt b/CC.Yi.DALFactory/T4StaticDalFactory.tt index 40388a29..f6194b8f 100644 --- a/CC.Yi.DALFactory/T4StaticDalFactory.tt +++ b/CC.Yi.DALFactory/T4StaticDalFactory.tt @@ -32,7 +32,7 @@ namespace CC.Yi.DALFactory I<#=k #>Dal Data = CallContext.GetData("<#=k #>Dal") as I<#=k #>Dal; if (Data == null) { - Data = new <#=k #>Dal(DbSessionFactory.GetCurrentDbSession().GetDbContent()); + Data = new <#=k #>Dal(); CallContext.SetData("<#=k #>Dal", Data); } return Data; diff --git a/CC.Yi.IBLL/IBaseBll.cs b/CC.Yi.IBLL/IBaseBll.cs index dae45507..456c9be7 100644 --- a/CC.Yi.IBLL/IBaseBll.cs +++ b/CC.Yi.IBLL/IBaseBll.cs @@ -11,6 +11,7 @@ namespace CC.Yi.IBLL //得到全部实体 #endregion IQueryable GetAllEntities(); + #region //通过表达式得到实体 #endregion @@ -36,11 +37,21 @@ namespace CC.Yi.IBLL #endregion T Add(T entity); + #region + //添加多个实体 + #endregion + bool Add(IEnumerable entities); + #region //更新实体 #endregion bool Update(T entity); + #region + //更新实体部分属性 + #endregion + bool Update(T entity, params string[] propertyNames); + #region //删除实体 #endregion @@ -54,6 +65,11 @@ namespace CC.Yi.IBLL #region //通过id列表删除多个实体 #endregion - int DeleteList(List ids); + bool Delete(IEnumerable ids); + + #region + //通过表达式删除实体 + #endregion + bool Delete(Expression> where); } } diff --git a/CC.Yi.IDAL/IBaseDal.cs b/CC.Yi.IDAL/IBaseDal.cs index a7b2d0cd..f4daf158 100644 --- a/CC.Yi.IDAL/IBaseDal.cs +++ b/CC.Yi.IDAL/IBaseDal.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -36,11 +37,20 @@ namespace CC.Yi.IDAL #endregion T Add(T entity); + #region + //添加多个实体 + #endregion + bool AddRange(IEnumerable entities); #region //更新单个实体 #endregion bool Update(T entity); + #region + //更新单个实体部分属性 + #endregion + bool Update(T entity, params string[] propertyNames); + #region //删除单个实体 #endregion @@ -50,5 +60,10 @@ namespace CC.Yi.IDAL //通过id删除实体 #endregion bool Detete(int id); + + #region + //删除多个实体 + #endregion + bool DeteteRange(IEnumerable entity); } } diff --git a/CC.Yi.Model/student.cs b/CC.Yi.Model/student.cs index 8a11819c..90ee09b7 100644 --- a/CC.Yi.Model/student.cs +++ b/CC.Yi.Model/student.cs @@ -11,6 +11,6 @@ namespace CC.Yi.Model [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int id { get; set; } - public int name { get; set; } + public string name { get; set; } } }