简体   繁体   中英

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.

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. 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).

There does not seem to be the EntityConfiguration class in the full release of entity framework. It appears to be only in the CTP that I am NOT using (a lot of the examples on the web use the CTP).

Also the following context takes strings that in no way seem to relate to the edmx or database.

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)?
  3. If I do use the edmx file how do I add my code first entities easily?
  4. How do the ObjectSets within the ObjectContext map to the database?

Thanks

EDIT I am using VS2010 professional and the classes that come with that. I see CTP4 is out so I assume the RTM version is not out yet. Is this correct?

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

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

Looks like I needed CTP4 found here

I also followed the walkthrough

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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