用VS Code创建ASP.NET Core MVC项目:MvcMoviesDemo。(DB First,连接MySql数据库)

本文介绍了如何使用VS Code创建一个.NET Core MVC项目,连接到MySql数据库,并通过dbcontext scaffold命令自动生成数据库表对应的类。文章详细讲述了安装NuGet程序集、创建数据库和表、解决生成类时遇到的问题以及实现增删查改功能的过程。
摘要由CSDN通过智能技术生成

目录

一、使用VS Code终端创建一个.Net Core MVC项目。

二、使用VS Code的NuGet Package Manager GUI插件添加相关的NuGet程序集。

三、在MySql数据库中创建MoviesDB数据库和Movie表,并插入少量测试数据。

四、使用dbcontext scaffold命令自动生成数据库表对应的对象类及数据库操作类。

4.1 Code First和Database First简介。

4.2 安装dotnet -ef命令工具。

4.3 把类型IDiagnosticsLogger注册到容器中。

4.4 重新更换MySql程序集。

4.5 执行dotnet ef dbcontext scaffold命令。

五、实现页面简单的增删查改功能。

5.1 页面效果。

5.2 代码集合。


一、使用VS Code终端创建一个.Net Core MVC项目。

输入以下命令:

// 切换到Projects文件夹下
cd Projects
 
// 创建名为MvcMoviesDemo的MVC项目
dotnet new mvc -o MvcMoviesDemo

 

二、使用VS Code的NuGet Package Manager GUI插件添加相关的NuGet程序集。

在VS Code中输入快捷键:Command + Shift + P,然后输入关键字NuGet Package Manager GUI进行搜索,选择回车。

依次添加以下程序集:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Relational

MySql.EntityFrameworkCore

添加完成后,可以在 MvcMoviesDemo.csproj 文件中看到以下程序集被自动添加。

三、在MySql数据库中创建MoviesDB数据库和Movie表,并插入少量测试数据。

在MySql数据库中的建库建表SQL语句:

create database MoviesDB;


use MoviesDB;


create table Movie(
ID int not null auto_increment,
Title nvarchar(100) not null,
ReleaseDate datetime not null, 
Genre nvarchar(100) null,
Price decimal(18, 2) not null,
Rating nvarchar(50) null,
primary key(ID)
);

在MySql数据库中向Movie表中插入几条数据:

INSERT INTO Movie
(
Title,
ReleaseDate,
Genre,
Price,
Rating
)
VALUES
(
'中国机长',
'2018-10-01 02:46:32',
'冒险',
45.00,
'9折'
);

INSERT INTO Movie
(
Title,
ReleaseDate,
Genre,
Price,
Rating
)
VALUES
(
'哪吒之魔童降世',
'2019-07-10 08:34:21',
'动画',
40.00,
'8.5折'
);

INSERT INTO Movie
(
Title,
ReleaseDate,
Genre,
Price,
Rating
)
VALUES
(
'阿凡达',
'2019-09-30 11:03:26',
'冒险',
55.00,
'9.8折'
);

INSERT INTO Movie
(
Title,
ReleaseDate,
Genre,
Price,
Rating
)
VALUES
(
'姜子牙',
'2021-06-28 12:45:02',
'动画',
42.00,
'8.8折'
);


INSERT INTO Movie
(
Title,
ReleaseDate,
Genre,
Price,
Rating
)
VALUES
(
'战狼2',
'2021-07-01 02:31:45',
'冒险',
48.00,
'9.5折'
);

四、使用dbcontext scaffold命令自动生成数据库表对应的对象类及数据库操作类。

4.1 Code First和Database First简介。

生成数据库表对应的类,有两种方式:

1>. 可以手动创建数据库表对应的类。

2>. 可以使用dbcontext scaffold命令自动产生数据库表对应的类。

EF Core生成数据库表及对应的类分为Code First和Database First两种方式,

Code First是指先手动创建数据库表对应的类,然后通过dotnet ef migrations命令生成相应的数据库表。

Database First是指先手动创建数据库表,然后通过dotnet ef dbcontext scaffold生成相应的类。

由于已经创建好了MoviesDB数据库和Movie表,采用Database First方式生成数据库表对应的类,在VS Code的终端中输入下列命令,然后在项目的Models文件夹中会自动生成数据库表对应的对象类Movie.cs及数据库操作类MoviesDBContext.cs。

dotnet ef dbcontext scaffold "server=127.0.0.1:3306;uid=root;pwd=123456;database=MoviesDB" MySql.EntityFrameworkCore -o Models -f

终端窗口出现以下报错信息:

无法执行,因为找不到指定的命令或文件。
可能的原因包括:
  *内置的 dotnet 命令拼写错误。
  *你打算执行 .NET 程序,但 dotnet-ef 不存在。
  *你打算运行全局工具,但在路径上找不到具有此名称且前缀为 dotnet 的可执行文件。

4.2 安装dotnet -ef命令工具。

出现以上错误的原因是给.Net做数据迁移,没有安装dotnet -ef命令工具。

按需输入下述命令之一:

// .Net Core 3.0 以上版本dotnet ef命令不再是sdk的一部分,需要单独安装
// 以下命令默认安装的是最新版本

dotnet tool install --global dotnet-ef


// 如果项目中使用的并不是最新版本,则还是不能使用,需要安装对应版本
// 以下命令安装的是指定版本

dotnet tool install --global dotnet-ef --version 3.1.1



// 安装错误可使用以下卸载命令:

dotnet tool uninstall --global dotnet-ef


// dotnet-ef命令工具安装成功后,还需要给项目引用NuGet包(如果没有引入):

dotnet add package Microsoft.EntityFrameworkCore.Design

 

安装完dotnet -ef命令工具后,再次执行以下命令,想自动生成数据库表对应的对象类及数据库操作类。

dotnet ef dbcontext scaffold "server=127.0.0.1:3306;uid=root;pwd=123456;database=MoviesDB" MySql.EntityFrameworkCore -o Models -f

结果出现以下报错信息:

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1[Microsoft.EntityFrameworkCore.DbLoggerCategory+Scaffolding]' while attempting to activate 'MySql.EntityFrameworkCore.Scaffolding.Internal.MySQLDatabaseModelFactory'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluarlize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1[Microsoft.EntityFrameworkCore.DbLoggerCategory+Scaffolding]' while attempting to activate 'MySql.EntityFrameworkCore.Scaffolding.Internal.MySQLDatabaseModelFactory'.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值