.NetCore通過EFCore操作數據庫


安裝nuget包

efcore官方支持的數據庫包括SQLServer、MySql、PostgreSQL、Sqlite
我們這里使用SQLServer數據庫

 

 添加數據庫上下文類和數據模型

 1 public class YFDbContext : DbContext
 2     {
 3         /// <summary>
 4         /// 構造函數
 5         /// </summary>
 6         public YFDbContext()
 7         {
 8 
 9         }
10         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
11         {
12             //private string ConnstrSqlServer = "server=服務器名稱;uid=登錄名稱;pwd=登錄密碼;database=數據庫名稱";
13             optionsBuilder.UseSqlServer(@"server=數據庫地址;uid=sa;pwd=數據庫密碼;database=CoreDB");
14             base.OnConfiguring(optionsBuilder);
15         }
16         /// <summary>
17         /// 通過依賴注入方式啟動的構造函數
18         /// </summary>
19         /// <param name="options"></param>
20         //public YFDbContext(DbContextOptions<YFDbContext> options) : base(options)
21         //{
22 
23         //}
24         public DbSet<UserInfo> UserInfo { get; set; }
25         public DbSet<RoleInfo> RoleInfo { get; set; }
26 
27         /// <summary>
28         /// 重寫Dispose方法,便於查看數據庫上下文什么時候釋放。
29         /// </summary>
30         public override void Dispose()
31         {
32             base.Dispose();
33             Console.WriteLine("\n***Dispose****\n\n");
34         }
35     }
YFDbContext.cs
1 public class UserInfo
2     {
3         public string Id { get; set; }
4         public string UserName { get; set; }
5         public string UserSex { get; set; }
6     }
UserInfo.cs
1 public class RoleInfo
2     {
3         public string Id { get; set; }
4         public string RoleName { get; set; }
5         public string RoleDescription { get; set; }
6     }
RoleInfo.cs

 添加測試控制器

 1 public class EFTestController : Controller
 2     {
 3         /// <summary>
 4         /// 測試EFCore插入數據
 5         /// 每次需要實例化數據庫上下文
 6         /// </summary>
 7         /// <returns></returns>
 8         public JsonResult TestInsert()
 9         {
10             List<UserInfo> uList;
11             using (var db=new YFDbContext())
12             {
13                 //1.新增
14                 UserInfo userInfo = new UserInfo()
15                 {
16                     Id = Guid.NewGuid().ToString("N"),
17                     UserName = "張三",
18                     UserSex = ""
19                 };
20                 //同步方法
21                 db.Add(userInfo);
22                 int count = db.SaveChanges();
23                 //異步方法
24                 //await _db.Set<UserInfo>().AddAsync(userInfo);
25                 //int count = await _db.SaveChangesAsync();
26                 Console.WriteLine($"成功插入{count}條數據");
27                 //2.查詢
28                 uList = db.Set<UserInfo>().ToList();
29                 foreach (var item in uList)
30                 {
31                     Console.WriteLine($"id為:{item.Id},名字為:{item.UserName},性別為:{item.UserSex}");
32                 }
33             }
34             return Json(uList);
35         }
36     }
EFTestController.cs

執行結果:

我這里使用了谷歌瀏覽器JsonView插件。

 

 

 升級:通過依賴注入方式獲取數據庫上下文

在appsettings.json中配置數據庫連接字符串

在Startup.cs文件ConfigureServices方法中添加服務

 

 

 

 

 改造控制器,通過依賴注入方式獲取數據庫上下文

 1 public class EFTestIOCController : Controller
 2     {
 3         private readonly YFDbContext _db;
 4         private readonly DbContextOptions<YFDbContext> _options;
 5         public EFTestIOCController(YFDbContext db, DbContextOptions<YFDbContext> options)
 6         {
 7             _db = db;
 8             _options = options;
 9         }
10         public IActionResult Index()
11         {
12             return View();
13         }
14         /// <summary>
15         /// 測試EFCore插入數據
16         /// 通過依賴注入方式獲取數據庫上下文
17         /// </summary>
18         /// <returns></returns>
19         public JsonResult TestInsert()
20         {
21             List<UserInfo> uList;
22             using (var db = new YFDbContext())
23             {
24                 //1.新增
25                 UserInfo userInfo = new UserInfo()
26                 {
27                     Id = Guid.NewGuid().ToString("N"),
28                     UserName = "張三",
29                     UserSex = ""
30                 };
31                 //同步方法
32                 db.Add(userInfo);
33                 int count = db.SaveChanges();
34                 
35                 Console.WriteLine($"成功插入{count}條數據");
36                 //2.查詢
37                 uList = db.Set<UserInfo>().ToList();
38                 foreach (var item in uList)
39                 {
40                     Console.WriteLine($"id為:{item.Id},名字為:{item.UserName},性別為:{item.UserSex}");
41                 }
42             }
43             return Json(uList);
44         }
45 }
EFTestIOCController.cs

執行結果:

 

 

 問題
再次調用http://localhost:5000/EFTestIOC/TestInsert方法或者使用異步方法插入數據時會報一下錯誤,該問題的原因是依賴注入方式的數據庫上下文生命周期

解決辦法:用 DbContextOptions 手工 new DbContext

System.ObjectDisposedException:“Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
”

 

 1 public async void TestMultInsert()
 2         {
 3             System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
 4             watch.Start();  //開始監視代碼運行時間
 5             using (var context = new YFDbContext(_options))
 6             {
 7 
 8                 for (int i = 0; i < 10; i++)
 9                 {
10                     //1.新增
11                     UserInfo userInfo = new UserInfo()
12                     {
13                         Id = Guid.NewGuid().ToString("N"),
14                         UserName = "ypf3",
15                         UserSex = ""
16                     };
17                     await context.Set<UserInfo>().AddAsync(userInfo);
18                     int count = await context.SaveChangesAsync();
19                     Console.WriteLine($"成功插入{count}條數據");
20                 }
21             }
22             watch.Stop();  //停止監視
23             TimeSpan timespan = watch.Elapsed;  //獲取當前實例測量得出的總時間
24             Console.WriteLine($"代碼執行時間:{timespan.TotalMilliseconds}");
25         }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM