asp.net webs制作(包括连接数据库)

本文介绍了如何使用ASP.NET Core创建Web应用并与MySQL数据库进行交互。内容涵盖数据库连接、数据操作(添加、查找和删除)以及各种数据库操作技巧,如设置复合主键、使用EF.Core进行数据操作、排序、预加载和非跟踪查询等。
摘要由CSDN通过智能技术生成

基本

自用
添加中
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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值