EntityFramework 7 开发纪录
博文目录:
- 暂时开发模式
- Code First 具体体现
- DbContext 配置
- Entity 映射关联配置
- Migration 问题纪录(已解决)
之前的一篇博文:EF7 Code First Only-所引发的一些“臆想”
写这篇博文的缘由是:因为这次 EF7 更新比较大,很多东西都是全新模式,而且 EF7 相关的资料实在太少,所以只能通过 GitHub 上的 Entity Framework Wiki 进行参考学习,但资源有限,而且坑也不少,没办法,自己动手,丰衣足食。
下面说下我用 EF7 开发项目的一些笔记(待补充):
暂时开发模式
说明:The EF7 NuGet packages use some new metadata that is only supported in NuGet 2.8.3 or higher.
EF7 目前只能通过 NuGet 进行管理,所以,首先确定你的 Visual Studio 中的 NuGet 为最新版本(最低支持 2.8.3,最新版本 3.0)。
- Visual Studio 2015 - No updates needed, a compatible version of NuGet is included.
- Visual Studio 2013 - You can download a compatible version from Visual Studio Gallery. A compatible version is also included in VS 2013 Update 4.
- Visual Studio 2010 and 2012 - You can download a compatible version from Visual Studio Gallery.
然后需要在 Tools –> NuGet Package Manager –> Package Manager Settings 中配置 Package Sources:https://www.myget.org/F/aspnetvnext/api/v2/,VS 2015 不需要进行添加。
我使用的是 VS 2015 开发的,所以 NuGet 不需要任何配置,使用 EF 之前,需要添加一个类库项目。
这是 VS 2015 中 ASP.NET 5 的三种模版,首先需要明确的是,ASP.NET 5 Class Library 项目可以在其他两个项目之前进行引用,但不能被其他非 ASP.NET 5 项目引用,相反,ASP.NET 5 项目也不能引用其他类型的类库项目,如果强行引用,就会抱下面错误:
所以说,如果你的 Web 项目为 ASP.NET 5,那你开发的所有类库项目必须为 ASP.NET 5 Class Library 类型的。
Code First 具体体现
创建 ASP.NET 5 Class Library 类型的 EF7 项目,像平常 EF 开发一样,我们需要在 EF7 项目中添加项,但你会发现,选择项模版中并没有“ADO.NET Entity Date Model”项。
EF6:
EF7:
“ADO.NET Entity Date Model”,就是“Code First Only”的具体表现,没办法,EF7 逼着你自行写实体代码。
DbContext 配置
EF7DbContext 示例代码:
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using System;
namespace EF7
{
public class EF7DbContext : DbContext
{
public DbSet<Entity> Entities { get; set; }
protected override void OnConfiguring(DbContextOptions builder)
{
builder.UseSqlServer(@"data source=.;initial catalog=EF7Db;integrated security=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>()
.ForRelational()
.Table("Entities");
modelBuilder.Entity<Entity>()
.Key(n => n.Id);
modelBuilder.Entity<Entity>()
.Property(t => t.Id)
.GenerateValuesOnAdd(false);
base.OnModelCreating(modelBuilder);
}
}
}
OnModelCreating 方法没有变化,变化的是内部实现,映射配置后面讲下,OnConfiguring 是新加入的,builder.UseSqlServer 的作用就是绑定连接字符串,相当于之前版本 App.config 中的 connectionStrings,这个配置也可以在 ASP.NET 5 Web 的 Startup.cs 中进行配置,如下:
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime.
public void ConfigureServices(IServiceCollection services)
{
// Add EF services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<CNBlogsNewsDbContext>();
//.AddDbContext<CNBlogsNewsDbContext>(options =>
//{
// //options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString"));
// options.UseSqlServer();
//});
// Add MVC services to the services container.
services.AddMvc();
// Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
// You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
// services.AddWebApiConventions();
}
}
AddEntityFramework 的配置模式有很多,比如上面配置中就不使用 EF7DbContext 中的连接字符串,而是读取 config.json 配置文件中的 ConnectionString,详细内容在 ASP.NET 5 记录中再进行说明,在 EF7DbContext 的示例代码中,我们会发现没有了 EF7DbContext 构造函数,之前都是在构造函数中写一大堆东西,比如:
public EF6DbContext()
: base("name=EF6Db")
{
this.Configuration.LazyLoadingEnabled = false;
Database.SetInitializer<EF6DbContext>(null);
}
这部分配置都移到 EF7DbContext 中的 OnConfiguring(DbContextOptions) 进行配置。
更多内容,请参考:Configuring a DbContext
Entity 映射关联配置
示例代码:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>()
.ForRelational()
.Table("Entities");
modelBuilder.Entity<Entity>()
.Key(n => n.Id);
modelBuilder.Entity<Entity>()
.Property(t => t.Id)
.GenerateValuesOnAdd(false);
modelBuilder.Entity<ChildEntity>()
.Key(n => n.Id);
modelBuilder.Entity<ChildEntity>()
.ManyToOne(n => n.Entity, t => t.ChildEntities)
.ForeignKey(t => t.EntityId);
base.OnModelCreating(modelBuilder);
}
对 Entity 属性的一些配置,我们也可以在属性的上面进行配置(比如 Key、Required、DataType 等),命令空间:System.ComponentModel.DataAnnotations,Table 配置是我无意间发现的,我原以为 EF7 不能对 Entity 进行表的重命名,之前我记得在 EF6 中是有 ToTable() 方法的,或者在 Entity 上面进行 Table() 属性配置,但在 EF7 中改为了 ForRelational,所在程序集为:EntityFramework.Relational,GenerateValuesOnAdd 的配置说明是否为 identity,之前 EF 版本配置为:HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity),Entity 之间的关联配置:
- OneToOne:一对一
- OneToMany:一对多
- ManyToOne:多对一
EF7 Entity 之间的关联配置更加简单明了,EF 之前版本配置(HasOptional 或 HasRequired):
HasOptional(x => x.ParentMessage)
.WithMany()
.Map(x => x.MapKey("ParentID"))
//.HasForeignKey(c => c.ParentID)
.WillCascadeOnDelete(false);
Migration 问题纪录
参考:Using EF7 in Traditional .NET Applications
这是 EF7 的官方使用说明,其中有提到 Migration(迁移)的部分用法,其实很简单,总共就四步:
Install-Package EntityFramework.SqlServer –Pre
Install-Package EntityFramework.Commands -Pre
Add-Migration MyFirstMigration
Apply-Migration
EF7DbContext 并不需要任何配置,但试过之后会发现,一大堆的问题,而且解决方案也搜不到,已经困扰一两天的时间了,下面纪录下过程。
之前写过一篇 EF Code First 的博文,里面有提到 EF 代码迁移的使用方法(非 EF7 版本),大致为:
Enable-Migrations
Add-Migration Update-NewType-Name
Update-Database
EF 7 代码迁移命令的完整说明(来自 get-help {命令名称} -full):
Use-DbContext [-Context] <string> [[-Project] <string>] [<CommonParameters>]
Add-Migration [-Name] <string> [[-Context] <string>] [[-Project] <string>] [<CommonParameters>]
Apply-Migration [[-Migration] <string>] [[-Context] <string>] [[-Project] <string>] [<CommonParameters>]
Update-Database [[-Migration] <string>] [[-Context] <string>] [[-Project] <string>] [<CommonParameters>]
Script-Migration [[-From] <string>] [[-To] <string>] [[-Context] <string>] [[-Project] <string>] [-Idempotent] [<CommonParameters>]
首先,按照EF7 Wiki 说明,在 Package Manager Console 中输入:Add-Migration MyFirstMigration 命令,会报如下错误:
异常完整信息:Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was in.
什么意思呢?直接说就是找不到“Add-Migration”命令,EF7 Migration 的所有命令管理都在 EntityFramework.Commands 程序集,所以我们使用 Migration 之前,都必须 NuGet 安装一下,找不到“Add-Migration”命令,这个问题困扰我很久,也没有找到相关资料,因为 Migration 的命令方式都是 PowerShell,我对这东西一窍不通,没办法,后来我尝试不使用 EF7,而是使用 EF6 进行 Migration 配置,发现是可以的,这就很奇怪,回过头再用 EF7 输入命令“Add-Migration”,就会报另一种错误:
异常完整信息:Join-Path : Cannot bind argument to parameter 'Path' because it is null.At C:\Users\yuezhongxin\Desktop\ConsoleApp1\packages\EntityFramework.6.1.1\tools\EntityFramework.psm1:713 char:28
什么意思?就是因为“Path”参数问题,不能加载“Add-Migration”命令,和上面异常不同的是,这个异常给出错误地址了:“EntityFramework.6.1.1\tools\EntityFramework.psm1”,但有个问题是,我使用的是 EF7,为什么会报 EntityFramework.6.1.1 的异常,这个问题也困扰我很久,最后在一篇博文中找到答案及解决方式:Entity Framework 5.0系列之Code First数据库迁移,大致意思是说 Migration 命令没有加载最新版本的 EntityFramework,所以需要在 Package Manager Console 中手动配置一下:
Import-Module C:\Users\yuezhongxin\.kpm\packages\EntityFramework.Commands\7.0.0-beta1\tools\EntityFramework.psd1
Install-Package EntityFramework.Commands -IncludePrerelease
在 EF 之前版本中 EntityFramework.psd1 文件位置都会在 EntityFramework 程序集文件中,但在 EF7 中,被分离在了 EntityFramework.Commands 程序集文件中了,第二步的作用是重新加载程序集。
异常完整信息:The names of some imported commands from the module 'EntityFramework' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
Import-Module EF6 是成功的,但 Import-Module EF7 就会出现上面的警告信息,具体原因不得而知,在 Package Manager Console 中输入“Add-Migration MyFirstMigration”命令,会出现下面异常:
异常完整信息:Add-Migration : Cannot bind argument to parameter 'Path' because it is null.At line:1 char:1
但输入“get-help Add-Migration -full”命令(查看 Add-Migration 帮助信息),就会发现 Add-Migration 命令并没有任何问题,也就是说 EntityFramework.Commands 是可以使用的:
其实问题出现的原因无非就是两点:
- EntityFramework.Commands 中的 Migration 命令
- EF7DbContext 配置
网上关于 EF7 Migration 的资料实在少得可怜,这个问题我也只探究到这一步,毕竟还要做事,就纪录到这,等待后续解决!
》》》》》》》》》》》》》》》》》》》》》华丽分割线,EF7 Migration 问题解决《《《《《《《《《《《《《《《《《《《《《
原本已经放弃 EF7 Migration,这篇博文也只是做一个问题记录,但博文发布出来有一位园友 codepat,在评论中附带了一个 EF7 Migration 参考地址:http://www.asp.net/vnext/overview/aspnet-vnext/vc,主要是说明 EF7 Migration 的操作通过 KVM 完成,我上面所有的尝试都是通过 Package Manager Console 命令完成的,后来 EF wiki 上也更新了一篇 KVM 命令的博文:Migrations commands (high-level experience),但文中只是简单说了几个命令,并没有详细讲述,“Migrations commands (high-level experience)”,这个命名不知道是不是说明原来 Package Manager Console 命令已经不能使用,也就是上面一直出现的报错问题,还是 EF7 Migration 只能通过 KVM 命令进行操作,下面纪录下使用 KVM 的操作步骤:
- 命令行运行(安装 KVM):
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))"
- 退出命令行,再次打开,输入命令:
KVM upgrade
- cd 转到 EF7 项目下(project.json 所在目录),如:
cd C:\Users\yuezhongxin\Desktop\EF7\src\EF7
- 增加迁移命令:
k ef migration add initial
- 应用迁移命令:
k ef migration apply
project.json 示例代码:
{
"version": "1.0.0-*",
"dependencies": {
"EntityFramework.SqlServer": "7.0.0-beta1",
"EntityFramework.Commands": "7.0.0-beta1",
"EntityFramework": "7.0.0-beta1",
"EntityFramework.Migrations": "7.0.0-beta1",
"EntityFramework.Relational": "7.0.0-beta1"
},
"commands": {
"ef": "EntityFramework.Commands"
},
"frameworks" : {
"aspnet50" : {
"dependencies": {
}
},
"aspnetcore50" : {
"dependencies": {
"System.Runtime": "4.0.20-beta-22231"
}
}
}
}
运行操作图:
困扰几天的问题终于解决了,这种感觉比中 500W 的彩票还要好,再次感谢园友 codepat。
珍贵的参考资料:
- Getting Started with EF7 Nightly Builds
- What is EF7 all about
- MusicStore
- Using EF7 in Traditional .NET Applications
- Configuring a DbContext
- Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7
- Migrations commands (high-level experience)
- Code First Migrations
- Entity Framework 5.0系列之Code First数据库迁移
- EF7 NuGet Commands
- EF Migrations Command Reference
- Using EF7 in Windows Phone & Store Applications
EntityFramework 7 开发纪录的更多相关文章
- 设置EntityFramework 在开发时自动更新数据库
1. NuGet 下载EntityFramework. 2. 定义Context 和 打开NuGet 命令 执行 Enable-Migrations , Libaray.DAL.Migrations. ...
- 爱与恨的抉择:ASP.NET 5+EntityFramework 7
EF7 的纠缠 ASP.NET 5 的无助 忘不了你的好 一开始列出的这个博文大纲,让我想到了很久之前的一篇博文:恋爱虽易,相处不易:当EntityFramework爱上AutoMapper,只不过这 ...
- ASP.NET 5+EntityFramework 7
爱与恨的抉择:ASP.NET 5+EntityFramework 7 EF7 的纠缠 ASP.NET 5 的无助 忘不了你的好 一开始列出的这个博文大纲,让我想到了很久之前的一篇博文:恋爱虽易,相 ...
- EF7学习资料整理
EntityFramework 7 开发纪录 http://www.cnblogs.com/xishuai/archive/2014/11/28/ef7-develop-note.html Entit ...
- 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用
上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...
- (转)EntityFramework之领域驱动设计实践
EntityFramework之领域驱动设计实践 - 前言 EntityFramework之领域驱动设计实践 (一):从DataTable到EntityObject EntityFramework之领 ...
- EntityFramework之领域驱动设计实践
EntityFramework之领域驱动设计实践 - 前言 EntityFramework之领域驱动设计实践 (一):从DataTable到EntityObject EntityFramework之领 ...
- Entity Framework与ADO.Net及NHibernate的比较
Entity Framework 是微软推荐出.NET平台ORM开发组件, EF相对于ado.net 的优点 (1)开发效率高,Entity Framework的优势就是拥有更好的LINQ提供程序. ...
- 1.NopCommerce下载与安装
NoCommerce是基于微软ASP.NET MVC + EntityFramework 技术开发的一套开源电子商城系统,其架构与设计非常精妙被誉为.NET商城的经典之作. 作为一个.NET程序爱好者 ...
随机推荐
- IIS 连接 oracle报Oracle.DataAccess版本错误解决办法
通过IIS连接oracle时报“Could not load file or assembly 'Oracle.DataAccess, Version=2.112.3.0, Culture=neutr ...
- 站内全文检索服务来了,Xungle提供免费全文检索服务
免费站内全文检索服务来了,是的,你没听错.全文检索相信大家已经不太陌生,主流检索服务有sphinx.xunsearch等,但这些都受服务器限制,对于中小站长尤其是没有服务器实现就困难了,随着数据量的增 ...
- 修复jLink V9固件小记
网上买了个山寨jLink V9.3 plus,号称不掉固件的,不过固件最终还是掉了,现象是:插上去红灯亮,发现jLink但是驱动无法安装.估计是固件丢失了,放G搜了一圈发现修复固件都是V8的,但是倒找 ...
- JQM开发Tips
1.radio Button 点击后有时候有高亮样式,有时候没有 解决方案: $("#task_form label").click(function () { $("# ...
- 启动项目的时候报驱动错误: not support oracle driver 1.0
问题:今天在使用pom导入oracle14的包时候发现怎么都下载不过来.网上查了一下发现是因为Oracle驱动需要官方授权,所以在pom.xml文件直接配置,无法下载成功. 解决方法就是下载oracl ...
- CharSequence cannot be resolved. It is indirectly referenced from required .class files
最近在写项目的时候发现会莫名其妙的出现这个编译错误,网上查了下发现自己安装的是JDK1.8造成的 原因:JDK1.8版本现在还不稳定 解决方法:卸载JDK1.8,安装JDK1.7 扩展:发现安装JDK ...
- maven filter 乱码,MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8 sequence.
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactI ...
- [.net 面向对象程序设计进阶] (17) 多线程(Multithreading)(二) 利用多线程提高程序性能(中)
[.net 面向对象程序设计进阶] (17) 多线程(Multithreading)(二) 利用多线程提高程序性能(中) 本节要点: 上节介绍了多线程的基本使用方法和基本应用示例,本节深入介绍.NET ...
- 建站技能get(1)— Asp.net MVC快速集成ckplayer网页视频播放器
故事背景大概是这样的,我厂两年前给山西晋城人民政府做了一个门户网站(地址:http://jccq.cn/),运行了一年多固若金汤,duang的有一天市场部门过来说,新闻管理模块带视频的内容播放不了了. ...
- JavaScript面试时候的坑洼沟洄——表达式与运算符
上篇博客JavaScript面试时候的坑洼沟洄--数据类型总结了一下JavaScript数据类型几转换的相关知识,很多朋友可能和我一样,买了书后对数据类型啊.运算符啊.语句啊都是扫两眼或直接略过的,自 ...