当前位置:   article > 正文

ASP.NET Core Entity Framework(EF) 数据库访问 SqlSugar_entityframework sugarsql

entityframework sugarsql

ASP.NET Core 依赖注入
ASP.NET Core Entity Framework Core
ASP.NET Core Application to Existing Database (Database First)(设置连接数据库字符串,上下文)
EF Core 5.0 中的新增功能

.NET Core 使用 Autofac 依赖注入
EF Core 3.x 中包含的中断性变更

--------------------------Entity Framework Core--------------------------
1、数据库连接字符串  

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Information",
  5. "Microsoft": "Warning",
  6. "Microsoft.Hosting.Lifetime": "Information"
  7. }
  8. },
  9. "AllowedHosts": "*",
  10. "ConnectionStrings": {
  11. "SchoolContext": "Server=(localdb)\\mssqllocaldb;Database=SchoolContext;Trusted_Connection=True;MultipleActiveResultSets=true"
  12. }
  13. }

2、添加 TodoContext 数据库上下文  

  1. using Microsoft.EntityFrameworkCore;
  2. namespace TodoApi.Models
  3. {
  4. public class TodoContext : DbContext
  5. {
  6. public TodoContext(DbContextOptions<TodoContext> options)
  7. : base(options)
  8. { }
  9. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  10. {
  11. #region 打印SQL语句
  12. optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder =>
  13. {
  14. builder.AddConsole();
  15. }));
  16. #endregion
  17. }
  18. protected override void OnModelCreating(ModelBuilder modelBuilder)
  19. {
  20. modelBuilder.Entity<sys_resource>().ToTable("sys_resource");
  21. modelBuilder.Entity<sys_resource>(entity =>
  22. {
  23. #region 单主键
  24. //entity.HasKey(e => e.id).HasName("PK_sys_resource");
  25. #endregion
  26. #region 多主键
  27. //entity.HasKey(e => new { e.id, e.r_id }).HasName("PK_sys_resource");
  28. #endregion
  29. });
  30. base.OnModelCreating(modelBuilder);
  31. }
  32. public DbSet<sys_resource> Resources { get; set; }
  33. public DbSet<TodoItem> TodoItems { get; set; }
  34. }
  35. public class sys_resource
  36. {
  37. [Key]//主键
  38. [DatabaseGenerated(DatabaseGeneratedOption.Identity)]//自增
  39. [Column("resource_code")]//列名
  40. public int resource_code { get; set; }
  41. public string resource_name { get; set; }
  42. public string descriptions { get; set; }
  43. public string enable { get; set; }
  44. public int sort { get; set; }
  45. public int modify_code { get; set; }
  46. public string modify_name { get; set; }
  47. public DateTime modify_time { get; set; }
  48. public string status { get; set; }
  49. }
  50. }

*、Controller 调用 Service

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.Extensions.Logging;
  10. using Sso.Repository;
  11. using Sso.Server.Models;
  12. namespace Sso.Server.Controllers
  13. {
  14. //[Authorize]
  15. public class HomeController : Controller
  16. {
  17. private readonly ILogger<HomeController> _logger;
  18. private readonly ICategoryService _categorySvc;
  19. public HomeController(ILogger<HomeController> logger, ICategoryService categorySvc)
  20. {
  21. _logger = logger;
  22. _categorySvc = categorySvc;
  23. }
  24. public IActionResult Index()
  25. {
  26. _categorySvc.GetAllList();
  27. return View();
  28. }
  29. }
  30. }

*、ICategoryService【Service 调用 DbContext 上下文】

  1. public class CategoryService : ICategoryService
  2. {
  3. private readonly TodoContext _dbContext;
  4. public CategoryService(TodoContext context)
  5. {
  6. _dbContext = context;
  7. }
  8. public List<Categorys> GetAllList()
  9. {
  10. List<Categorys> list = new List<Categorys>();
  11. try
  12. {
  13. list = _dbContext.TodoItems.OrderByDescending(o => o.Id).Where(o => o.State != "D").ToList();
  14. }
  15. catch (Exception ex)
  16. {
  17. }
  18. return list;
  19. }
  20. }

3、更新数据库上下文类  
*
4、Startup.cs  注册数据库上下文
ASP.NET Core 通过 依赖关系注入 进行生成

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddRazorPages();
  4. services.AddDbContext<SchoolContext>(options =>
  5. options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
  6. }
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. /*
  4. * 配置连接数据库
  5. */
  6. var connection=@"Data Source=.; Initial Catalog=dbCoffee; Uid=sa; Pwd=000000;";
  7. services.AddDbContext<ModelEntities>(options => options.UseSqlServer(connection));
  8. /*
  9. * 依赖注入
  10. */
  11. services.AddTransient<ICategoryService, CategoryService>();
  12. services.AddTransient<ILanguageService, LanguageService>();
  13. services.AddTransient<IProductService, ProductService>();
  14. services.AddTransient<IProductStepService, ProductStepService>();
  15. services.AddTransient<IProductStructureService, ProductStructureService>();
  16. /*
  17. * 批量注入 ok
  18. */
  19. foreach (var item in GetAssemblyName("***.Repository"))
  20. {
  21. services.AddTransient(item.Key, item.Value);
  22. }
  23. foreach (var item in GetAssemblyName123("***.Repository"))
  24. {
  25. foreach (var typeArray in item.Value)
  26. {
  27. if (!typeArray.Name.StartsWith("IRepository"))
  28. services.AddTransient(typeArray, item.Key);
  29. }
  30. }
  31. }
  32. private Dictionary<Type, Type> GetAssemblyName(string assemblyName)
  33. {
  34. var result = new Dictionary<Type, Type>();
  35. if (!String.IsNullOrEmpty(assemblyName))
  36. {
  37. Assembly assembly = Assembly.Load(assemblyName);
  38. List<Type> ts = assembly.GetTypes().ToList();
  39. foreach (var item in ts.Where(x => x.IsClass && !x.IsAbstract && !x.IsGenericType))
  40. result.Add(item.GetInterfaces().FirstOrDefault(x => !x.Name.StartsWith("IRepository")), item);
  41. }
  42. return result;
  43. }
  44. private Dictionary<Type, Type[]> GetAssemblyName123(string assemblyName)
  45. {
  46. var result = new Dictionary<Type, Type[]>();
  47. if (!String.IsNullOrEmpty(assemblyName))
  48. {
  49. Assembly assembly = Assembly.Load(assemblyName);
  50. List<Type> ts = assembly.GetTypes().ToList();
  51. foreach (var item in ts.Where(x => x.IsClass && !x.IsAbstract && !x.IsGenericType))
  52. result.Add(item, item.GetInterfaces());
  53. }
  54. return result;
  55. }

5、注册数据库上下文  

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
  4. services.AddControllers();
  5. }

6、创建数据库  
context.Database.EnsureCreated();
如果有上下文的数据库,则 EnsureCreated 方法不执行任何操作。 如果没有数据库,则它将创建数据库和架构。
*、
*、
*、
*、
--------------------------Dapper--------------------------
*、
services.AddTransient<IDbConnection>((sp) => new SqlConnection(Configuration.GetConnectionString("DefaultConnection")));
*、
*、
--------------------------SqlSugar--------------------------
1、管理 NuGet 程序包
     sqlSugarCore

  1. services.AddSqlSugarClient<DbFactory>((sp, op) =>
  2. {
  3. op.ConnectionString = sp.GetService<IConfiguration>().GetConnectionString("***");
  4. op.DbType = DbType.MySql;
  5. op.IsAutoCloseConnection = true;
  6. op.InitKeyType = InitKeyType.Attribute;
  7. op.IsShardSameThread = true;
  8. });
  9. ///或 一下待测试
  10. Assembly assemblys = Assembly.Load("QuestionnaireSurvey.BLL");
  11. Assembly assemblysInterFace = Assembly.Load("QuestionnaireSurvey.IBLL");
  12. var typesInterface = assemblysInterFace.GetTypes();
  13. var typesImpl = assemblys.GetTypes();
  14. foreach (var item in typesInterface)
  15. {
  16. var name = item.Name.Substring(1);
  17. string implBLLImpName = name + "Server";
  18. var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));
  19. if (impl != null)
  20. {
  21. services.AddTransient(item, impl);
  22. }
  23. }
  24. //注入数据层
  25. services.AddTransient(typeof(DbSqlContext));
  26. //注入仓储
  27. services.AddTransient(typeof(IRepository<>), typeof(Repository<>));

*、
*、
*、

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/134950?site
推荐阅读
相关标签
  

闽ICP备14008679号