简体   繁体   English

实体框架核心模型

[英]Entity Framework Core models

I have built a ASP.NET Core MVC application that connects to MySQL.我已经构建了一个连接到 MySQL 的 ASP.NET Core MVC 应用程序。 I wanted to enhance the solution by adding Entity Framework because it automatically generates entities and models for you.我想通过添加实体框架来增强解决方案,因为它会自动为您生成实体和模型。 But reading about this new version (EF Core), it looks like you have to create the models in code then run a script to create the database.但是阅读这个新版本 (EF Core) 时,您似乎必须在代码中创建模型,然后运行脚本来创建数据库。 That seems backwards, what is the benefit if you don't want to create the database at runtime?这似乎是倒退,如果您不想在运行时创建数据库有什么好处?

I thought Entity Framework was the opposite, you could create the database first, then add connect it in Visual Studio through a nice UI and it would generate everything for you.我认为 Entity Framework 正好相反,你可以先创建数据库,然后通过一个漂亮的 UI 在 Visual Studio 中添加它,它会为你生成一切。 Why is it reversed now?为什么现在反了? I would rather maintain the database in MySQL, then fetch / sync the changes in Visual Studio.我宁愿在 MySQL 中维护数据库,然后在 Visual Studio 中获取/同步更改。

It is true that Entity Framework Core (for now, at least) only supports the Code First approach, but that only means that the option to generate classes through EDMX files and T4 (normally using the visual designer) is gone.的确,Entity Framework Core(至少目前)仅支持 Code First 方法,但这仅意味着通过 EDMX 文件和 T4(通常使用可视化设计器)生成类的选项消失了。

You have two options for Code First, just as you do in Entity Framework 6: Code First 有两个选项,就像在 Entity Framework 6 中一样:

  1. From scratch.从头开始。 Create your classes as you want, you design your database through the classes.根据需要创建类,通过类设计数据库。
  2. By reverse-engineering the database to create the classes.通过对数据库进行逆向工程来创建类。 You can see here how to do this: Getting Started with EF Core on ASP.NET Core with an Existing Database .您可以在此处查看如何执行此操作: 使用现有数据库在 ASP.NET Core 上使用 EF Core

Both options will leave you tied only to your POCOs and you can decide whether you want to use migrations or not.这两个选项都会让您只与您的 POCO 相关联,您可以决定是否要使用迁移。

What worked for me was Pomelo.EntityFrameworkCore.MySql对我有用的Pomelo.EntityFrameworkCore.MySql

The run this command with a connection string:使用连接字符串运行此命令:

dotnet ef dbcontext scaffold "Server=localhost;Database=ef;User=root;Password=123456;" "Pomelo.EntityFrameworkCore.MySql"

Use

 -o Models 

to generate classes in the Models directory在 Models 目录中生成类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM