在VS的程序包管器理控制台中无法识别Add-Migration
等EF相关的命令,是因为没有安装Microsoft.EntityFrameworkCore.Tools
解决办法:
// language: powershell
Install-Package Microsoft.EntityFrameworkCore.Tools
Entity Framework
在VS的程序包管器理控制台中无法识别Add-Migration
等EF相关的命令,是因为没有安装Microsoft.EntityFrameworkCore.Tools
解决办法:
// language: powershell
Install-Package Microsoft.EntityFrameworkCore.Tools
EntityFramework这个.NET 的 ORM框架,可以代码优先(code first),也可以数据库优先(database first),本文主要介绍数据库优先 database first 的使用方法:
先在Package Manager Console中安装 Microsoft.EntityFrameworkCore.Tools
包:
Install-Package Microsoft.EntityFrameworkCore.Tools
然后使用下面的命令扫描数据库,该命令根据数据库连接串扫描数据库,并生成相应的模型类。
Scaffold-DbContext "Server=127.0.0.1;User ID=root;Password=123456;Database=worksummary_net;" Pomelo.EntityFrameworkCore.MySql -OutputDir Data\Entities
扫描完成后,就可以在项目中使用EF进行数据库操作了。
使用 dotnet tool update --global dotnet-ef
将全局工具dotnet-ef
更新到最新的可用版本。
如果在项目中本地安装了这些工具,请使用 dotnet tool update dotnet-ef
。
通过将 --version
追加到命令来安装特定版本。 有关更多详细信息,请参阅 dotnet 工具文档的更新部分。
参考:https://learn.microsoft.com/zh-cn/ef/core/cli/dotnet#update-the-tools
在使用EF命令进行迁移时,遇到了VS2022 包管理控制台 找不到 add-migration 命令的错误。
解决办法:
使用everything搜索 EntityFrameworkCore.psd1,然后在程序包管理控制台中执行命令:import-module EntityFrameworkCore.psd1的全路径
例如:
import-module C:\Users\wujie\.nuget\packages\microsoft.entityframeworkcore.tools\7.0.0\tools\EntityFrameworkCore.psd1 -Verbose
出现黄色警告不用管:
EF的迁移命令:
dotnet ef migrations add Init-o Data\Migrations
Entity framework 中比较日期 ,使用linq的写法:
var totalCount = db.CallLog.Where(x => x.CallTime.Year == DateTime.Now.Year && x.CallTime.Month == DateTime.Now.Month && x.CallTime.Day == DateTime.Now.Day).Count();
分别比较年月日,虽然不好看,但是可以正常工作。
EntityFramework Linq 查询中不能使用int.parse
,否则报错,报错信息如下:
报错信息:LINQ to Entities does not recognize the method ‘Int32 Parse(System.String)’ method, and this method
var data = from v in db.Vip
join b in db.Business on v.BusinessId equals b.Id
where v.Level == int.Parse(level) // 这样写会报错
select new VipInfoModel
{
VipName = v.VipName,
Level = v.Level.Value,
BusinessId = v.BusinessId.Value,
BusinessName = b.Name,
DisplayName = b.DisplayName
};
解决方案:把int.parse
拿到外面
var _level = int.Parse(level);
var data = from v in db.Vip
join b in db.Business on v.BusinessId equals b.Id
where v.Level == _level
select new VipInfoModel
{
VipName = v.VipName,
Level = v.Level.Value,
BusinessId = v.BusinessId.Value,
BusinessName = b.Name,
DisplayName = b.DisplayName
};
EF7让实体类的某个字段不映射到数据库
添加注解:
[System.ComponentModel.DataAnnotations.Schema. NotMapped]
EF7的迁移还是挺简单的,在命令行中执行以下迁移命令:
k ef migration add initial
k ef migration apply
说明,k
就是早期的.net core。
code first 常用命令
Enable-Migrations -EnableAutomaticMigrations -Force //code first启用迁移,并允许自动迁移
Enable-Migrations
第一次开启迁移时执行
添加迁移
add-Migration xxx
update-database //更新数据库
MSDN说明见这里: http://msdn.microsoft.com/en-us/library/dn579398.aspx