当前位置:Gxlcms > 数据库问题 > 九、.net core用orm继承DbContext(数据库上下文)方式操作数据库

九、.net core用orm继承DbContext(数据库上下文)方式操作数据库

时间:2021-07-01 10:21:17 帮助过:118人阅读

一、创建一个DataContext普通类继承DbContext

技术图片

二、配置连接字符串(MySql/SqlServer都可以)

技术图片

  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace DotNetCore.Models
  7. {
  8. public class DataContext:DbContext
  9. {
  10. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  11. {
  12. //配置MySql连接字符串/SqlServer连接字符串皆可
  13. optionsBuilder.UseMySql("Server=47.94.174.85;Database=testDb; User=testDb;Password=testDb;");
  14. }
  15. public class t_testModel
  16. {
  17. public int id { get; set; }
  18. public string name { get; set; }
  19. public string pass { get; set; }
  20. }
  21. //添加表实体
  22. public DbSet<t_testModel> friends { get; set; }
  23. }
  24. }  

三、在控制器里面写查询操作

 

  1. DataContext context = new DataContext();
  2. List<t_testModel> list = context.friends.ToList();
  3. return Content(list.ToString());

 技术图片

四、数据库表对应的结构

  1. DROP TABLE IF EXISTS `friends`;
  2. CREATE TABLE `friends` (
  3. `id` int(3) NOT NULL,
  4. `name` varchar(8) NOT NULL,
  5. `pass` varchar(20) NOT NULL
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  7. INSERT INTO `friends` VALUES (‘4‘, ‘王六‘, ‘dasd‘);

 

总结所作的操作

1、创建DataContext类继承DbContext(一个类文件)  

2、控制器里面写查询操作 

九、.net core用orm继承DbContext(数据库上下文)方式操作数据库

标签:list()   value   arc   cte   操作   core   content   builder   inf   

人气教程排行