.Net6使用EFCore在SqlServer上创建数据库

  本文介绍如何在SqlServer上创建一个新的数据库。项目便用VS2022编辑器,运行在.Net6 Asp.Net Core WebApi项目模板中,数据库程序运行在阿里云服务器的Windows Server2019中,使用的是SqlServer2022版本,EntityFrameworkCore的版本为6.0.25,数据库显示程序为SQL Server Management Studio19.1。采用CodeFirst创建数据库,即先有代码数据结构,再有数据库。
  建议新建一个.Net6 Web Api项目作为测试,并且项目命名、文件夹命名、文件命名都和我一样,否则会出现各种问题。没有搭建数据库程序的请先看博客:在服务器(Window Server 2019)上安装SQL Server数据库

1.准备工作

查看你安装SqlServer程序的公网IP地址,如果安装在本地则不用看了,我的是在阿里云控制台里显示的。
在这里插入图片描述

确保你安装了SqlServer程序在一台电脑上,并使用用户名密码可以在SQL Server Management Studio中成功连接数据库。如图所示为连接成功:
在这里插入图片描述

2.配置EFCore环境

打开VS2022,新建一个.Net6 Asp.Net Core WebApi项目。
在这里插入图片描述
项目名为:test_EFCore
建议和我一样
在这里插入图片描述
使用.Net6,点击创建。
在这里插入图片描述
右键项目,点击”管理NuGet程序包“。
在这里插入图片描述
在浏览中找到这两个包:需要安装6.0.x版本的,要和你的.Net版本对应。你是.Net8,就安装8.0.x版本的。
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
在这里插入图片描述
安装Microsoft.EntityFrameworkCore.SqlServer6.0,要和你的.Net版本对应。
在这里插入图片描述
安装Microsoft.EntityFrameworkCore.Tools6.0,要和你的.Net版本对应。
在这里插入图片描述

3.编写数据库代码

新建文件夹:Entities
在这里插入图片描述
在这个文件夹里新建两个cs文件:Product.cs、ProductCategory.cs。
这两个文件对应了数据库的两个表,名称为“Id”的属性会被EFCore识别为主键。
在这里插入图片描述
Product.cs文件内容:

namespace test_EFCore.Entities
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string ImageURL { get; set; }
        public decimal Price { get; set; }
        public int Qty { get; set; }
        public int CategoryId { get; set; }
    }
}

ProductCategory.cs文件内容:

namespace test_EFCore.Entities
{
    public class ProductCategory
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

再新建一个cs文件:test_EFCoreDbContext.cs
在这里插入图片描述
test_EFCoreDbContext.cs文件内容:

using Microsoft.EntityFrameworkCore;
using test_EFCore.Entities;

namespace test_EFCore
{
    public class test_EFCoreDbContext : DbContext
    {
        public test_EFCoreDbContext(DbContextOptions<test_EFCoreDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            //Products
            //Beauty Category
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 1,
                Name = "Glossier - Beauty Kit",
                Description = "A kit provided by Glossier, containing skin care, hair care and makeup products",
                ImageURL = "/Images/Beauty/Beauty1.png",
                Price = 100,
                Qty = 100,
                CategoryId = 1

            });
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 2,
                Name = "Curology - Skin Care Kit",
                Description = "A kit provided by Curology, containing skin care products",
                ImageURL = "/Images/Beauty/Beauty2.png",
                Price = 50,
                Qty = 45,
                CategoryId = 1

            });
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 3,
                Name = "Cocooil - Organic Coconut Oil",
                Description = "A kit provided by Curology, containing skin care products",
                ImageURL = "/Images/Beauty/Beauty3.png",
                Price = 20,
                Qty = 30,
                CategoryId = 1

            });
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 4,
                Name = "Schwarzkopf - Hair Care and Skin Care Kit",
                Description = "A kit provided by Schwarzkopf, containing skin care and hair care products",
                ImageURL = "/Images/Beauty/Beauty4.png",
                Price = 50,
                Qty = 60,
                CategoryId = 1

            });
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 5,
                Name = "Skin Care Kit",
                Description = "Skin Care Kit, containing skin care and hair care products",
                ImageURL = "/Images/Beauty/Beauty5.png",
                Price = 30,
                Qty = 85,
                CategoryId = 1

            });
            //Electronics Category
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 6,
                Name = "Air Pods",
                Description = "Air Pods - in-ear wireless headphones",
                ImageURL = "/Images/Electronic/Electronics1.png",
                Price = 100,
                Qty = 120,
                CategoryId = 3

            });
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 7,
                Name = "On-ear Golden Headphones",
                Description = "On-ear Golden Headphones - these headphones are not wireless",
                ImageURL = "/Images/Electronic/Electronics2.png",
                Price = 40,
                Qty = 200,
                CategoryId = 3

            });
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 8,
                Name = "On-ear Black Headphones",
                Description = "On-ear Black Headphones - these headphones are not wireless",
                ImageURL = "/Images/Electronic/Electronics3.png",
                Price = 40,
                Qty = 300,
                CategoryId = 3

            });

            //Add Product Categories
            modelBuilder.Entity<ProductCategory>().HasData(new ProductCategory
            {
                Id = 1,
                Name = "Beauty",
            });
            modelBuilder.Entity<ProductCategory>().HasData(new ProductCategory
            {
                Id = 2,
                Name = "Furniture",
            });
            modelBuilder.Entity<ProductCategory>().HasData(new ProductCategory
            {
                Id = 3,
                Name = "Electronics",
            });
            modelBuilder.Entity<ProductCategory>().HasData(new ProductCategory
            {
                Id = 4,
                Name = "Shoes",
            });

        }

        public DbSet<Product> Products { get; set; }
        public DbSet<ProductCategory> ProductCategories { get; set; }

    }
}

这个文件主要是用来生成数据库的,数据库有两个表:Products和ProductCategories,并OnModelCreating函数中预先放了一些初始数据。

4.配置数据库连接设置

在Program.cs文件中添加如下代码:

builder.Services.AddDbContext<test_EFCoreDbContext>(p =>
{
    p.UseSqlServer(builder.Configuration.GetConnectionString("SqlServer"));
});

在这里插入图片描述
在appsettings.json中加入数据库连接的字符串,这里有几个参数很重要!
server:这个是你服务器的IP地址,如果是本地的数据库则添入 localhost 或 127.0.0.1 ,如果是服务器上,则添入你服务器的公网IP地址。
uid:这个是你数据库的连接用户名。
pwd:这个是你数据库的连接密码。
database:这个是数据库的名称,一个数据库程序下可以有多个数据库。

  "ConnectionStrings": {
    "SqlServer": "server=**.***.***.***;uid=sa;pwd=*************;database=test_EFCore;TrustServerCertificate=true;"
  },

在这里插入图片描述

5.生成数据库

最后,打开你的“程序包管理控制台”。
在这里插入图片描述
输入命令:Add-Migration Init
Init是一个更新字符串,随便写就行,每次更新数据库时不能一样。
在这里插入图片描述
输入命令:Update-Database
此命令用于提交更新到数据库。
看到Done则为成功。
在这里插入图片描述
用SSMS打开数据库,可以看到新数据库的内容:
在这里插入图片描述

  • 16
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
连接 SQL Server 数据库.NET Core 中常见的操作之一。以下是在 .NET Core 中连接 SQL Server 数据库的步骤: 1. 在 .NET Core 项目中添加 NuGet 包:Microsoft.EntityFrameworkCore.SqlServer 和 Microsoft.EntityFrameworkCore.Tools。 2. 在程序的 Startup.cs 文件中配置数据库连接字符串。在 ConfigureServices 方法中添加以下代码: ``` services.AddDbContext<YourDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); ``` 其中,YourDbContext 是你的 DbContext 类型,"DefaultConnection" 是你的连接字符串名称。 3. 在 appsettings.json 文件中添加连接字符串: ``` "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true" } ``` 其中,"Server=(localdb)\\mssqllocaldb" 是本地 SQL Server 实例名称,"YourDatabaseName" 是你的数据库名称。 4. 创建 DbContext 类。例如: ``` using Microsoft.EntityFrameworkCore; namespace YourNamespace { public class YourDbContext : DbContext { public YourDbContext(DbContextOptions<YourDbContext> options) : base(options) { } public DbSet<YourModel> YourModels { get; set; } } } ``` 其中,YourModel 是你的实体类,可以通过 DbSet<YourModel> 属性访问。 5. 运行以下命令创建数据库迁移: ``` dotnet ef migrations add InitialCreate ``` 6. 运行以下命令将迁移应用到数据库: ``` dotnet ef database update ``` 7. 现在你可以在代码中使用 DbContext 访问数据库了。例如: ``` using (var context = new YourDbContext()) { var yourModel = new YourModel { Name = "YourName" }; context.YourModels.Add(yourModel); context.SaveChanges(); } ``` 以上是连接 SQL Server 数据库的基本步骤。当然,具体的实现可能会因为项目的不同而有所出入,但是以上步骤可以作为一个基础框架。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高思宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值