一、创建一个DataContext普通类继承DbContext
二、配置连接字符串(MySql/SqlServer都可以)
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; }
}
}
三、在控制器里面写查询操作
DataContext context = new DataContext();
List list = context.friends.ToList();
return Content(list.ToString());
四、数据库表对应的结构
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、控制器里面写查询操作
原文:https://www.cnblogs.com/fger/p/10630976.html