基本
自用
添加中
c# 基本的连接,操作等等
asp。net
数据库的连接
来源整理于多个网站
https://blog.csdn.net/andy5520/article/details/91956126
https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/razor-pages/?view=aspnetcore-3.1
https://www.runoob.com/aspnet/mvc-database.html
https://www.csdn.net/gather_22/Mtjacg3sMjg2MTItYmxvZwO0O0OO0O0O.html
1.创建 asp.net core web application
- 注意选择 web application
2.需要引用多个包 通过 Manage NuGet Package
- MySql.Data.EntityFrameworkCore
- MySql.Data
- Microsoft.EntityFrameworkCore
3.在models添加DBContext
public class TestDBContext:DbContext
{
public DbSet<Test> Tests {
get; set; }
public TestDBContext(DbContextOptions<TestDBContext> options) : base(options)
{
}
}
[Table("test")]
public class Test
{
public int id {
get; set; }//必须存在一个名为id的变量(貌似)不然会报错不存在 key value
public string ss {
get; set; }
}
[StringLength(50)]貌似可以限制string长度
[Key] 可为属性名不是id 设置为主键
若为符合主键
则可参考
http://msdn.microsoft.com/en-us/data/JJ591617.aspx#1.2
Configuring a Composite Primary Key
The following example configures the DepartmentID and Name properties to be the composite primary key of the Department type.
modelBuilder.Entity().HasKey(t => new { t.DepartmentID, t.Name });
4.配置文件 appsettings.json 中添加mysql 连接数据库字符串
"ConnectionStrings": {
"MysqlConnection": "Data Source=localhost;Database=Test;User ID=root;Password=123456;pooling=true;CharSet=utf8;port=3306;sslmode=none" }
database:数据库名
5.Startup.cs 添加代码
向方法名为 public void ConfigureServices(IServiceCollection services)
的方法中添加添加
var connection = Configuration.GetConnectionString("MysqlConnection");
services.AddDbContext<BooksDBContext>(options => options.UseMySQL(connection));
services.