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

本文介绍了如何在.NET Core中使用ORM(Entity Framework Core)并通过继承DbContext来操作MySQL数据库。首先,安装Pomelo.EntityFrameworkCore.MySql程序集,并配置连接字符串。接着,创建DataContext类,定义数据库实体和DbSet属性。在控制器中,利用依赖注入进行数据库查询。最后,将数据库连接字符串移至appsettings.json,并更新Startup类以使用DbContext。
摘要由CSDN通过智能技术生成

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

1cbfb319669e9d46bbaa1858fd104fa2.png

安装程序集:Pomelo.EntityFrameworkCore.MySql

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

020b9225c7f48308897d0c7e0b81c2d8.png

using Microsoft.EntityFrameworkCore;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace DotNetCore.Models

{

public class DataContext:DbContext

{

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

//配置MySql连接字符串/SqlServer连接字符串皆可

optionsBuilder.UseMySql("Server=47.94.174.85;Database=testDb; User=testDb;Password=testDb;");

}

public class t_testModel

{

public int id { get; set; }

public string name { get; set; }

public string pass { get; set; }

}

//添加表实体

public DbSet friends { get; set; }

}

}

这里注意:

optionsBuilder.UseMySql("Server=47.94.174.85;Database=testDb; User=testDb;Password=testDb;");//的你要安装Pomelo.EntityFrameworkCore.MySql

optionsBuilder.UseMySQL("Server=47.94.174.85;Database=testDb; User=testDb;Password=testDb;");//的你要安装MySql.Data.EntityFrameworkCore 这个UserMYSQL中MYSQL是大写的

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

DataContext context = new DataContext();

List list = context.friends.ToList();

return Content(list.ToString());

773e31f797a6c3d6ff0a624b61fc5847.png

四、数据库表对应的结构

DROP TABLE IF EXISTS `friends`;

CREATE TABLE `friends` (

`id` int(3) NOT NULL,

`name` varchar(8) NOT NULL,

`pass` varchar(20) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `friends` VALUES ('4', '王六', 'dasd');

总结所作的操作

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

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

四、数据连接属性应该存放在appsettings.json内

1、更改DbContext类内容如下所示

using Microsoft.EntityFrameworkCore;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace DotNetCore.Models

{

public class DataContext : DbContext

{

public DataContext(DbContextOptions options)

: base(options)

{

}

public class t_testModel

{

public int id { get; set; }

public string name { get; set; }

public string pass { get; set; }

}

//添加表实体

public DbSet friends { get; set; }

}

}

2、appsettings.json文件更改如下

{

"Logging": {

"IncludeScopes": false,

"LogLevel": {

"Default": "Warning"

}

},

"ConnectionStrings": {

"DefaultConnection": "Server=47.94.174.85;Database=testDb; User=testDb;Password=testDb;"

}

}

3、将Startup类里面的ConfigureServices替换成下列代码

public void ConfigureServices(IServiceCollection services)

{

services.AddDbContext(options =>

options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

services.AddMvc();

}

注意:鼠标放上去继续点击引用

19dd0dd3bbc82421a892696cf0e1c86c.png

4、控制器实现代码

DataContext context = new DataContext();

List list = context.friends.ToList();

return Content(list.ToString());

8fe3c12ec53687906036c18beedc9e13.png

c260e0c15159a38e054adf04eae2c5cf.png

我们点击运行吧 我们发现还是不可用。

我们换一种方式运行

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using DotNetCore.Models;

using static DotNetCore.Models.DataContext;

namespace DotNetCore.Controllers

{

public class HomeController : Controller

{

public readonly DataContext _context;

//构造函数,依赖注入数据库上下文就可以了

public HomeController(DataContext context)

{

_context = context;

}

public IActionResult Index()

{

List list = _context.friends.ToList();

return Content(list.ToString());

return View();

}

public IActionResult About()

{

ViewData["Message"] = "Your application description page.";

return View();

}

public IActionResult Contact()

{

ViewData["Message"] = "Your contact page.";

return View();

}

public IActionResult Error()

{

return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

}

}

}

0007a40afe66367d91be316df12aae1b.png

asp.netCore连接多个数据库参考:

b219218f650b430e0839a0d75fe78b29.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我理解了你的问题。关于 Hangfire、MySQL 和 ASP.NET Core 3.1 的使用,我可以给出一些异常解决的建议。 首先,确保你已经按照官方文档正确地安装和配置了 Hangfire 和 MySQL。然后,根据你遇到的异常,尝试以下解决方法: 1. "Could not load file or assembly 'MySql.Data' or one of its dependencies" 异常 这个异常通常是由于缺少 MySQL 数据库驱动程序引起的。你需要在项目中添加对 MySQL 数据库驱动程序的引用。可以通过 NuGet 包管理器来安装 MySQL.Data。 2. "Specified key was too long; max key length is 767 bytes" 异常 这个异常是由于 MySQL 的索引长度限制引起的。解决方法是,在你的 DbContext 类中覆盖 OnModelCreating 方法,将所有字符串属性的最大长度设置为 255。 ``` protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var property in modelBuilder.Model.GetEntityTypes() .SelectMany(t => t.GetProperties()) .Where(p => p.ClrType == typeof(string))) { property.SetMaxLength(255); } } ``` 3. "MySqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding" 异常 这个异常通常是由于 MySQL 连接超时引起的。解决方法是,在连接字符串中添加 Connection Timeout 参数,例如: ``` "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;Connection Timeout=60;" ``` 这将使连接超时时间为 60 秒。 希望这些解决方法能帮助你解决异常问题。如果你还有其他问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值