如何从Entity Framework中的.edmx文件生成数据库? [英] How can I generate the database from .edmx file in Entity Framework?

查看:316
本文介绍了如何从Entity Framework中的.edmx文件生成数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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:

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.

如果再次执行SQL,在已经存在的表名后面也会出现相同的错误数据库。

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

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

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

如何摆脱该错误并成功在.edmx中生成表?

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

我也无法在解决方案资源管理器中右键单击找到从上下文类继承自DBContext对象的选定类文件生成数据库的选项。我从Microsoft安装了Entity Framework 4.1,因此它应该出现在其中...如何获得生成数据库选项?

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?

推荐答案

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

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:


  1. 选择新连接

  2. 设置服务器名称:if您安装了它,只需键入。选择默认值。您还可以尝试(本地)

  3. 设置新数据库名称

  4. 将DDL脚本复制到SQL Server Management Studio的查询屏幕中

  5. 运行脚本以创建数据库

  1. Select new connection
  2. Set Server name: if you installed it, just type . to select default. You can also try (local)
  3. Set new database name
  4. Copy DDL script to your SQL server management studio's query screen
  5. Run the script to create your db

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

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

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

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:

 using System;
    using System.Collections.Generic;

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

上下文将只有一个表。

 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; }
    }

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

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.

 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();
            }
        }

这篇关于如何从Entity Framework中的.edmx文件生成数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆