2013年8月7日星期三

EF Code First First Experience

 

Code First name suggests is the first code, then the code generation of database development methods.

 

ado, direct to blow look:
in VS2010 in a new blank solution, then add two class library project: Model, DataAccess and a console project BreakAwayConsole. Are the entities, data access, console display.

 

project structure:

 

 

Description:

 

1. entity class Model

 

the library, there are two categories: Lodging (accommodation category), Destination (Things like)
Lodging class definition:

 
  
    /// <summary>
    /// 住宿类
    /// </summary>
public
class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; } //是否度假胜地

public Destination Destination { get; set; }
}
 
 

entity classes with you in the past more than the definition of a navigation attribute Destination. It is specified in EF foreign key relationship with the Lord.
Here is Destination class definition:

 
  
    /// <summary>
    /// 景点类
    /// </summary>
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }

public List<Lodging> Lodgings { get; set; }
}
 
 

also has a navigation property, or a List collection type. Popular point to understand: Destination , including many (List) a Lodging, is an attraction ( Destination) There are many accommodations (Lodging) place, so Destination class is: List Lodgings; while an accommodation (Lodging) where only one Attractions ( Destination) , so stay in the navigation category Lodging attribute is the Destination, rather than List .

 

2. data access DataAccess

 

need to reference the class library EntityFramework, and also need to add a reference to the class using System.Data.Entity, also need to add a reference to the Model class
EF database context to access the database through the database CRUD (add change search deleted), so we create a database access class inherits DbContext BreakAwayContext:

 
  
    public class BreakAwayContext : DbContext 
{
//以下是数据库上下文对象,以后对数据库的访问就用下面对象
public DbSet<CodeFirst.Model.Destination> Destinations { get; set; }
public DbSet<CodeFirst.Model.Lodging> Lodgings { get; set; }
}
 
 

context of this class is a database access classes, after every add an entity needs added.

 

3. Console BreakAwayConsole

 

This layer needs to be set as the startup project (right - Set as StartUp Project)
Program classes need to add the following references: Model, DataAccess class libraries and EntityFramework

 

then add a method to Program.cs:

 
  
        private static void InsertDestination() 
{
var destination = new CodeFirst.Model.Destination
{
Country
= "Indonesia",
Description
= "EcoTourism at its best in exquisite Bali",
Name
= "Bali"
};
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
 
 

simple linq written to the database Destination insert a data table. Then in the Main method to call InsertDestination method.

 

late we definitely want to keep the modified Model in the entity class, so I add a Main method:

 
  
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CodeFirst.DataAccess.BreakAwayContext>());
 
 

means: If the entity class has changed, then regenerate what database (DropCreateDatabaseIfModelChanges). Using this method they have to add the reference: using System.Data.Entity;

 

everything is ready, we F5 to run under the console project, and see if I can generate the entity class code corresponding context object database and the database through a data insertion < / span>
just wait a few seconds, reported a ProviderIncompatibleException fault, as shown:

 

 

means not find the database. EF default database is:. \ SQLEXPRESS, if no local SQLEXPRESS, EF will try LocalDb \ v11.0 (included in VS2012 in)

 

I use sql 2008 Enterprise Edition database, you must specify the database in the configuration file for the console project to add a configuration file App.Config:

 
  
<?xml version="1.0" encoding="utf-8" ?> 
<configuration>
<connectionStrings>
<add name="BreakAwayContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=BreakAwayConfigFile;Trusted_Connection=True"/>
<add name="My_Test" providerName="System.Data.SqlClient" connectionString="Server=.;Database=MyBreakAwayDb;Trusted_Connection=true" />
</connectionStrings>
</configuration>
 
 

we wrote two nodes, name values ​​were BreakAwayContext and My_Test, BreakAwayContext and database context class name exactly as we go BreakAwayContet class and add a constructor, Let context can find the database:

 
  
public BreakAwayContext(): base("name=BreakAwayContext") 
{ }
 
 

Note: name = BreakAwayContext can not write, because the default is to find the configuration file name and the class name the same database connection string that BreakAwayContext, then the generated database is: BreakAwayConfigFile. If we want to specify your own to find which database connection string, that directly modify name = My_Test can, so to find the configuration file in the second database connection string, and the resulting database is naturally: MyBreakAwayDb. Straightforward.

 

EF course there are other ways to find a database connection string, for example: DbConnection, connection factories, and other details, please self-learning, here only the most commonly used.

 

At this point, we'll run the next generation of the program will be able to correct the database:

 

 

observe'll find: Multi generates a EdmMetadata table, which is to monitor changes in the entity class table, follow-up article will be introduced.

 

Meanwhile, EF each table are generated for the primary key, but also set up a corresponding foreign key relationships. (EF primary key is the default mapping rules, foreign key because we added to the entity class navigation properties). All other fields are the default nullable type, size is the default max. Of course, the project is certainly not so that each field can be empty. Will be described in detail later in the article.

 

 

ok, this is over, Demo released along with the next article. Next article stresses EF Lane default mapping and how to use Data Annotations and the Fluent API configuration database mappings.
3ks 4 reading

 

 
  Series of articles Navigation:   
       
  1. EF Code First First Experience
  2.    
  3. EF's default mapping and how to use Data Annotations and the Fluent API configuration database mapping
  4.    
  5. there are a lot to be continued ....
  6.   
 

没有评论:

发表评论