如何从Entity Framework中的.edmx文件生成数据库?

时间:2022-01-13 06:02:41

I have had to suddenly switch to working on Code First Entity Framework 4.1. I started off not knowing anything about this framework but in the last 8 hrs I am now much more comfortable having read blogs and articles.

我不得不突然转向使用Code First Entity Framework 4.1。我开始对这个框架一无所知,但在过去的8小时里,我现在阅读博客和文章会更加舒服。

This blog in particular is one of the best blogs I have seen so far on the topic but the steps given do not match with my experience. In particular, I need more focus on the 3rd and 4th steps ('Create the Model' and 'Swap to DbContext Code Generation', respectively). I am unable to generate the database from my defined EntitySet. I am getting the SQL and I can execute but I'm getting the following error:

特别是这个博客是迄今为止我在这个主题上看到的最好的博客之一,但是给出的步骤与我的经验不符。特别是,我需要更多地关注第3和第4步(分别是'创建模型'和'交换到DbContext代码生成')。我无法从我定义的EntitySet生成数据库。我得到SQL,我可以执行,但我收到以下错误:

Could not locate entry in sysdatabases for "MyBD" database . No entry found with that name. Make sure that the name is entered correctly entity framework.

If I execute the SQL again, I get the same error following the names of tables that already exist in database.

如果我再次执行SQL,我会在数据库中已存在的表的名称后面得到相同的错误。

If refresh the DataConnection in Server Explorer, there are no such tables created as I defined in Entity Framework.

如果在服务器资源管理器中刷新DataConnection,则不会创建我在Entity Framework中定义的表。

How can I get rid of this error and successfully generate the tables in my .edmx?

如何摆脱此错误并在我的.edmx中成功生成表格?

Also I am unable to find the option on right-click in Solution Explorer to "Generate Database" from selected class file that has the context class inherited from the DBContext object. I installed the Entity framework 4.1 from Microsoft, so it should appear there... How can I get the Generate Database option?

此外,我无法在解决方案资源管理器中右键单击选项类文件中的“生成数据库”,该文件具有从DBContext对象继承的上下文类。我从Microsoft安装了Entity framework 4.1,因此它应该出现在那里......我如何获得Generate Database选项?

2 个解决方案

#1


5  

If you are creating the database from the model, you need to select the empty model first. Here are the other steps to create db:

如果要从模型创建数据库,则需要先选择空模型。以下是创建db的其他步骤:

  1. Select new connection
  2. 选择新连接
  3. Set Server name: if you installed it, just type . to select default. You can also try (local)
  4. 设置服务器名称:如果安装了它,只需键入即可。选择默认值。你也可以尝试(本地)
  5. Set new database name
  6. 设置新的数据库名称
  7. Copy DDL script to your SQL server management studio's query screen
  8. 将DDL脚本复制到SQL Server管理工作室的查询屏幕
  9. Run the script to create your db
  10. 运行脚本以创建数据库

After running the script, you will have the initial table. Config file will have connection string named as container name.

运行脚本后,您将拥有初始表。配置文件将具有名为容器名称的连接字符串。

Now, when you want to switch to code generation similar to example with TT files, you can right click and add code generation. It will create partial class for the entity model and one file for dbcontext. Similar to this:

现在,当您想切换到与TT文件类似的代码生成时,您可以右键单击并添加代码生成。它将为实体模型创建部分类,为dbcontext创建一个文件。与此类似:

 using System;
    using System.Collections.Generic;

    public partial class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Context will have only one table.

上下文只有一个表。

 public partial class PersonModelContainer : DbContext
    {
        public PersonModelContainer()
            : base("name=PersonModelContainer")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Contact> Contacts { get; set; }
    }

You dont need TT model. You can add these files directly. You need one context class inheriting from DbContext and one partial class file for each type of entity. If you make a change to model, EF will detect that. You need to define Db initializer. For the sample demo on that webpage, you can add initializer to another method. If it is a web project, you add this init function to Global.asax->application_Start for the initial development. You have different options for initializers. I use drop and create for initial development.

你不需要TT模型。您可以直接添加这些文件。您需要一个继承自DbContext的上下文类和一个用于每种实体类型的部分类文件。如果您对模型进行更改,EF将检测到该模型。您需要定义Db初始化程序。对于该网页上的示例演示,您可以将初始化程序添加到另一个方法。如果它是一个Web项目,则将此init函数添加到Global.asax-> application_Start以进行初始开发。初始化程序有不同的选项。我使用drop和create进行初始开发。

 static void InitDbCheck()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PersonModelContainer>());
            using (var db = new PersonModelContainer())
            {
                //accessing a record will trigger to check db.
                int recordCount = db.Contacts.Count();
            }
        }

        static void Main(string[] args)
        {



            using (var db = new PersonModelContainer())
            {
                // Save some data
                db.Contacts.Add(new Contact { Name = "Bob" });
                db.Contacts.Add(new Contact { Name = "Ted" });
                db.Contacts.Add(new Contact { Name = "Jane" });
                db.SaveChanges();

                // Use LINQ to access data
                var people = from p in db.Contacts
                             orderby p.Name
                             select p;

                Console.WriteLine("All People:");
                foreach (var person in people)
                {
                    Console.WriteLine("- {0}", person.Name);
                }

                // Change someones name
                db.Contacts.First().Name = "Janet";
                db.SaveChanges();
            }
        }

#2


17  

Here's the definitive guide from MSDN on

这是MSDN上的权威指南

How to: Generate a Database from a Conceptual Model (Entity Data Model Tools) [.edmx] file.

如何:从概念模型(实体数据模型工具)[.edmx]文件生成数据库。

Copy/Pasting here just for the sake of completeness:

复制/粘贴只是为了完整起见:

To generate a database from a conceptual model

从概念模型生成数据库

1 - Add an .edmx file to your project.

1 - 将.edmx文件添加到项目中。

For information about adding an .edmx file to a project, see How to: Create a New .edmx File (Entity Data Model Tools) and How to: Add an Existing .edmx File (Entity Data Model Tools).

有关将.edmx文件添加到项目的信息,请参见如何:创建新的.edmx文件(实体数据模型工具)和如何:添加现有的.edmx文件(实体数据模型工具)。

2 - Build the conceptual model.

2 - 构建概念模型。

You can use the ADO.NET Entity Data Model Designer (Entity Designer) to create entities and relationships or you can manually edit the .edmx file to build a conceptual model. For more information, see Implementing Advanced Entity Framework Features and CSDL, SSDL, and MSL Specifications.

您可以使用ADO.NET实体数据模型设计器(实体设计器)创建实体和关系,也可以手动编辑.edmx文件以构建概念模型。有关更多信息,请参阅实现高级实体框架功能和CSDL,SSDL和MSL规范。

NoteNote When you build the conceptual model, warnings about unmapped entities and associations may appear in the Error List. You can ignore these warnings because the Create Database Wizard will add the storage model and mapping information (see step 3).

注意注意在构建概念模型时,有关未映射的实体和关联的警告可能会出现在错误列表中。您可以忽略这些警告,因为“创建数据库向导”将添加存储模型和映射信息(请参阅步骤3)。

3 - Right-click an empty space on the Entity Designer surface and select Generate Database from Model.

3 - 右键单击​​“实体设计器”表面上的空白区域,然后选择“从模型生成数据库”。

The Choose Your Data Connection Dialog Box of the Generate Database Wizard (Entity Data Model Tools) is displayed.

将显示“生成数据库向导”(“实体数据模型工具”)的“选择数据连接”对话框。

4 - Click the New Connection button or select an existing connection button from the drop-down list to provide a database connection.

4 - 单击“新建连接”按钮或从下拉列表中选择现有连接按钮以提供数据库连接。

You must supply a database connection so that column types for the target database can be determined based on property types in your model, and so that connection string information can be added to your application. Note that supplying connection information does not initiate data definition language (DDL) generation.

您必须提供数据库连接,以便可以根据模型中的属性类型确定目标数据库的列类型,以便可以将连接字符串信息添加到应用程序中。请注意,提供连接信息不会启动数据定义语言(DDL)生成。

5 - Click Next.

5 - 单击“下一步”。

The Create Database Wizard generates data definition language for creating a database. The generated DDL is displayed in the Summary and Settings Dialog Box (Generate Database Wizard).

“创建数据库向导”生成用于创建数据库的数据定义语言。生成的DDL显示在“摘要和设置”对话框(“生成数据库向导”)中。

6 - Click Finish.

6 - 单击“完成”。

Upon completion, the Create Database Wizard does the following:

完成后,“创建数据库向导”将执行以下操作:

Generates the store schema definition language (SSDL) and mapping specification language (MSL) that correspond to the provided conceptual schema definition language (CSDL). The .edmx file is updated with the generated SSDL and MSL. Note that the wizard overwrites existing SSDL and MSL.

生成与提供的概念架构定义语言(CSDL)对应的商店架构定义语言(SSDL)和映射规范语言(MSL)。使用生成的SSDL和MSL更新.edmx文件。请注意,向导会覆盖现有的SSDL和MSL。

Saves the generated DDL in the location specified in the Save DDL As text box. For more information about the generated DDL, see Database Generation Rules (Generate Database Wizard).

将生成的DDL保存在“将DDL另存为”文本框中指定的位置。有关生成的DDL的详细信息,请参阅数据库生成规则(生成数据库向导)。

NoteNote If a storage model is already defined when you run the Create Database Wizard, the generated DDL will contain a DROP TABLE statement and DROP CONSTRAINT statement for each EntitySet and each AssociationSet (respectively) that are inferred from the storage model.

注意注意如果在运行“创建数据库向导”时已定义存储模型,则生成的DDL将包含从存储模型推断的每个EntitySet和每个AssociationSet(分别)的DROP TABLE语句和DROP CONSTRAINT语句。

Adds connection string information to your App.config or Web.config file.

将连接字符串信息添加到App.config或Web.config文件中。

It is important to note that the Create Database Wizard does not execute the generated DDL. To create the database schema that corresponds to your conceptual model, you must execute the generated DDL independently (for example, execute the DDL in SQL Server Management Studio).

请务必注意,“创建数据库向导”不会执行生成的DDL。要创建与概念模型对应的数据库模式,必须单独执行生成的DDL(例如,在SQL Server Management Studio中执行DDL)。

#1


5  

If you are creating the database from the model, you need to select the empty model first. Here are the other steps to create db:

如果要从模型创建数据库,则需要先选择空模型。以下是创建db的其他步骤:

  1. Select new connection
  2. 选择新连接
  3. Set Server name: if you installed it, just type . to select default. You can also try (local)
  4. 设置服务器名称:如果安装了它,只需键入即可。选择默认值。你也可以尝试(本地)
  5. Set new database name
  6. 设置新的数据库名称
  7. Copy DDL script to your SQL server management studio's query screen
  8. 将DDL脚本复制到SQL Server管理工作室的查询屏幕
  9. Run the script to create your db
  10. 运行脚本以创建数据库

After running the script, you will have the initial table. Config file will have connection string named as container name.

运行脚本后,您将拥有初始表。配置文件将具有名为容器名称的连接字符串。

Now, when you want to switch to code generation similar to example with TT files, you can right click and add code generation. It will create partial class for the entity model and one file for dbcontext. Similar to this:

现在,当您想切换到与TT文件类似的代码生成时,您可以右键单击并添加代码生成。它将为实体模型创建部分类,为dbcontext创建一个文件。与此类似:

 using System;
    using System.Collections.Generic;

    public partial class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Context will have only one table.

上下文只有一个表。

 public partial class PersonModelContainer : DbContext
    {
        public PersonModelContainer()
            : base("name=PersonModelContainer")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Contact> Contacts { get; set; }
    }

You dont need TT model. You can add these files directly. You need one context class inheriting from DbContext and one partial class file for each type of entity. If you make a change to model, EF will detect that. You need to define Db initializer. For the sample demo on that webpage, you can add initializer to another method. If it is a web project, you add this init function to Global.asax->application_Start for the initial development. You have different options for initializers. I use drop and create for initial development.

你不需要TT模型。您可以直接添加这些文件。您需要一个继承自DbContext的上下文类和一个用于每种实体类型的部分类文件。如果您对模型进行更改,EF将检测到该模型。您需要定义Db初始化程序。对于该网页上的示例演示,您可以将初始化程序添加到另一个方法。如果它是一个Web项目,则将此init函数添加到Global.asax-> application_Start以进行初始开发。初始化程序有不同的选项。我使用drop和create进行初始开发。

 static void InitDbCheck()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PersonModelContainer>());
            using (var db = new PersonModelContainer())
            {
                //accessing a record will trigger to check db.
                int recordCount = db.Contacts.Count();
            }
        }

        static void Main(string[] args)
        {



            using (var db = new PersonModelContainer())
            {
                // Save some data
                db.Contacts.Add(new Contact { Name = "Bob" });
                db.Contacts.Add(new Contact { Name = "Ted" });
                db.Contacts.Add(new Contact { Name = "Jane" });
                db.SaveChanges();

                // Use LINQ to access data
                var people = from p in db.Contacts
                             orderby p.Name
                             select p;

                Console.WriteLine("All People:");
                foreach (var person in people)
                {
                    Console.WriteLine("- {0}", person.Name);
                }

                // Change someones name
                db.Contacts.First().Name = "Janet";
                db.SaveChanges();
            }
        }

#2


17  

Here's the definitive guide from MSDN on

这是MSDN上的权威指南

How to: Generate a Database from a Conceptual Model (Entity Data Model Tools) [.edmx] file.

如何:从概念模型(实体数据模型工具)[.edmx]文件生成数据库。

Copy/Pasting here just for the sake of completeness:

复制/粘贴只是为了完整起见:

To generate a database from a conceptual model

从概念模型生成数据库

1 - Add an .edmx file to your project.

1 - 将.edmx文件添加到项目中。

For information about adding an .edmx file to a project, see How to: Create a New .edmx File (Entity Data Model Tools) and How to: Add an Existing .edmx File (Entity Data Model Tools).

有关将.edmx文件添加到项目的信息,请参见如何:创建新的.edmx文件(实体数据模型工具)和如何:添加现有的.edmx文件(实体数据模型工具)。

2 - Build the conceptual model.

2 - 构建概念模型。

You can use the ADO.NET Entity Data Model Designer (Entity Designer) to create entities and relationships or you can manually edit the .edmx file to build a conceptual model. For more information, see Implementing Advanced Entity Framework Features and CSDL, SSDL, and MSL Specifications.

您可以使用ADO.NET实体数据模型设计器(实体设计器)创建实体和关系,也可以手动编辑.edmx文件以构建概念模型。有关更多信息,请参阅实现高级实体框架功能和CSDL,SSDL和MSL规范。

NoteNote When you build the conceptual model, warnings about unmapped entities and associations may appear in the Error List. You can ignore these warnings because the Create Database Wizard will add the storage model and mapping information (see step 3).

注意注意在构建概念模型时,有关未映射的实体和关联的警告可能会出现在错误列表中。您可以忽略这些警告,因为“创建数据库向导”将添加存储模型和映射信息(请参阅步骤3)。

3 - Right-click an empty space on the Entity Designer surface and select Generate Database from Model.

3 - 右键单击​​“实体设计器”表面上的空白区域,然后选择“从模型生成数据库”。

The Choose Your Data Connection Dialog Box of the Generate Database Wizard (Entity Data Model Tools) is displayed.

将显示“生成数据库向导”(“实体数据模型工具”)的“选择数据连接”对话框。

4 - Click the New Connection button or select an existing connection button from the drop-down list to provide a database connection.

4 - 单击“新建连接”按钮或从下拉列表中选择现有连接按钮以提供数据库连接。

You must supply a database connection so that column types for the target database can be determined based on property types in your model, and so that connection string information can be added to your application. Note that supplying connection information does not initiate data definition language (DDL) generation.

您必须提供数据库连接,以便可以根据模型中的属性类型确定目标数据库的列类型,以便可以将连接字符串信息添加到应用程序中。请注意,提供连接信息不会启动数据定义语言(DDL)生成。

5 - Click Next.

5 - 单击“下一步”。

The Create Database Wizard generates data definition language for creating a database. The generated DDL is displayed in the Summary and Settings Dialog Box (Generate Database Wizard).

“创建数据库向导”生成用于创建数据库的数据定义语言。生成的DDL显示在“摘要和设置”对话框(“生成数据库向导”)中。

6 - Click Finish.

6 - 单击“完成”。

Upon completion, the Create Database Wizard does the following:

完成后,“创建数据库向导”将执行以下操作:

Generates the store schema definition language (SSDL) and mapping specification language (MSL) that correspond to the provided conceptual schema definition language (CSDL). The .edmx file is updated with the generated SSDL and MSL. Note that the wizard overwrites existing SSDL and MSL.

生成与提供的概念架构定义语言(CSDL)对应的商店架构定义语言(SSDL)和映射规范语言(MSL)。使用生成的SSDL和MSL更新.edmx文件。请注意,向导会覆盖现有的SSDL和MSL。

Saves the generated DDL in the location specified in the Save DDL As text box. For more information about the generated DDL, see Database Generation Rules (Generate Database Wizard).

将生成的DDL保存在“将DDL另存为”文本框中指定的位置。有关生成的DDL的详细信息,请参阅数据库生成规则(生成数据库向导)。

NoteNote If a storage model is already defined when you run the Create Database Wizard, the generated DDL will contain a DROP TABLE statement and DROP CONSTRAINT statement for each EntitySet and each AssociationSet (respectively) that are inferred from the storage model.

注意注意如果在运行“创建数据库向导”时已定义存储模型,则生成的DDL将包含从存储模型推断的每个EntitySet和每个AssociationSet(分别)的DROP TABLE语句和DROP CONSTRAINT语句。

Adds connection string information to your App.config or Web.config file.

将连接字符串信息添加到App.config或Web.config文件中。

It is important to note that the Create Database Wizard does not execute the generated DDL. To create the database schema that corresponds to your conceptual model, you must execute the generated DDL independently (for example, execute the DDL in SQL Server Management Studio).

请务必注意,“创建数据库向导”不会执行生成的DDL。要创建与概念模型对应的数据库模式,必须单独执行生成的DDL(例如,在SQL Server Management Studio中执行DDL)。