博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Entity Framework】Model First Approach
阅读量:4578 次
发布时间:2019-06-08

本文共 1364 字,大约阅读时间需要 4 分钟。

EF中的model first

所谓mf, 就是使用vs提供的edm designer去设计model,然后将设计好的model使用vs在指定的数据库中生成数据库即可. 当你的项目既没有数据库也没有code的时候, 推荐你在项目中选用model first就行.

先来看个例子

  1. 打开vs, 新建一个console app,
    1216080-20190209113510772-876148760.png
  2. 打开nuget找到ef安装到项目上
    1216080-20190209105942250-1478086617.png
  3. add一个ado edm item
    1216080-20190209110103715-1595405843.png
    此时会出现一个弹出窗口, vs2017会有四个选项如下:
    1216080-20190209110234891-1002539941.png
    选择empty edm designer. 这是为model first设计的.其他的不是了.
  4. 点击finish之后会看到edmx的设计页面.以及model browser.
    1216080-20190209110455359-504612431.png
  5. 在diagram页面右键点击选择add一个entity
    下图是我创建完成的几个entity
    1216080-20190209110652099-2044670986.png
  6. 创建完设计好的entity之后, 在model browser上右键点击generate database from
    model
    1216080-20190209112032743-219825352.png
    此时会出现一个弹出窗体, 提示你按照说明配置一个db connection:
    1216080-20190209113336819-1746967741.png
  7. 配置完成后会在项目中生成一个model.edmx.sql的文件, 在vs上直接运行这个文件生成数据库就行了.
    1216080-20190209113156707-1269532183.png
  8. 数据库创建完后如果还需要再次修改entity的edm, 改完再次选择generate db from model就行. DDL文件会被修改, 再次执行文件,就会在对应的数据库中完成修改内容.
  9. 到此为止model first approach的一个demo就完成了.

model first模式下对于已经部署的数据库的修改

首先说明一点, model first与DB first都没有和code first类似的migration功能.

所以在官网的教程中也提到过以下:

"The script that is generated will drop all existing tables and then recreate the schema from scratch. This may work for local development but is not a viable for pushing changes to a database that has already been deployed. If you need to publish changes to a database that has already been deployed, you will need to edit the script or use a schema compare tool to calculate a migration script."

所以一般对于已经部署的数据库, 如果想更改edmx, 那么最好先对数据库进行更改后, 在edmx上右键点击后选择update model from database, 否则你可能会丢失部署环境的数据库中的数据.我觉得就是因为这一点, 很多情况下, 尽量不要选择model first approach.

参考资料

转载于:https://www.cnblogs.com/it-dennis/p/10357260.html

你可能感兴趣的文章