简体   繁体   English

代码首先使用EntityFramework 4链接到数据库

[英]Code first linking to database with EntityFramework 4

I am delving into the EntityFramework 4 code first of entities approach and I am getting stuck on how to take the ObjectContext / Entities and link them to a database. 我首先研究实体方法的EntityFramework 4代码,然后陷入如何采用ObjectContext / Entities并将它们链接到数据库的问题。

I have looked at varous sites on [msdn][1] and [blogs][2] about how to use all of this but they all fail in talking about how to create a database that the entities will be saved in or don't take the code first apprach. 我已经看过[msdn] [1]和[blogs] [2]上的各种站点,这些站点如何使用所有这些站点,但是它们都在谈论如何创建将实体保存或不保存的数据库方面首先采用代码。 I know I can create an edmx file and generate sql from that but since I am writing my entities first this file is empty and through the designer I don't see a way of adding my entities without duplicating effort (in creating all the entities/fields etc). 我知道我可以创建一个edmx文件并从中生成sql,但由于我首先编写实体,因此该文件为空,并且通过设计器,我看不到一种无需重复劳动即可添加实体的方法(在创建所有实体/字段等)。

There does not seem to be the EntityConfiguration class in the full release of entity framework. 完整版本的实体框架中似乎没有EntityConfiguration类。 It appears to be only in the CTP that I am NOT using (a lot of the examples on the web use the CTP). 它似乎只是我未使用的CTP(网络上的许多示例都使用CTP)。

Also the following context takes strings that in no way seem to relate to the edmx or database. 另外,以下上下文采用的字符串似乎与edmx或数据库无关。

public class EntityContext : ObjectContext
{
    public EntityContext()
        : base("name=ExampleEntities", "ExampleEntities")
    {
        ContextOptions.LazyLoadingEnabled = true;

        Users = CreateObjectSet<User>();
    }

    public IObjectSet<User> Users { get; set; }
}

So the question is. 问题是。

  1. How do I create a database schema that maps to my entities? 如何创建映射到我的实体的数据库架构?
  2. Should I use an edmx file at all or create my own database file (.mdf)? 我应该使用edmx文件还是创建自己的数据库文件(.mdf)?
  3. If I do use the edmx file how do I add my code first entities easily? 如果确实使用edmx文件,如何轻松添加代码优先实体?
  4. How do the ObjectSets within the ObjectContext map to the database? ObjectContext中的ObjectSet如何映射到数据库?

Thanks 谢谢

EDIT I am using VS2010 professional and the classes that come with that. 编辑我正在使用VS2010专业版以及随附的类。 I see CTP4 is out so I assume the RTM version is not out yet. 我看到CTP4退出了,所以我认为RTM版本还没有发布。 Is this correct? 这个对吗?

将此添加到application_start事件以创建数据库:

Database.SetInitializer<YourObjectContextClass>(new RecreateDatabaseIfModelChanges<YourObjectContextClass>());

Looks like I needed CTP4 found here 看起来我需要在这里找到CTP4

I also followed the walkthrough 我也按照演练

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

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