[ORM] Entity Framework (1) CodeFirst Quick Start, ormcodefirst

Source: Internet
Author: User

[ORM] Entity Framework (1) CodeFirst Quick Start, ormcodefirst

Entity Framework is an O/R Mapping solution developed by Microsoft Based on ADO. NET.
Object relationship ing (English:Object Relational ing, AbbreviationORMIs a program technology used to convert data of different types of systems in object-oriented programming languages.

 

Download: Install-Package EntityFramework-Version 6.1.3 (7.0 only in CodeOnly Mode)

This section provides a technical overview: database installation, DB First, Model First, Code First (important), DbContext, DbSet, CRUD examples, data migration, and transaction management.

 

Install LocalDB and SQL Server

  LocalDb is provided by visual studio for development and usage. Running is a process rather than a service.

Location: C: \ Program Files \ Microsoft SQL Server \ 110 \ Tools \ Binn \ SqlLocalDB.exe (this is the location of vs 2013. Use the VS2013 developer tool to enter sqllocaldb)

SQL Server adopts the service mode to facilitate connection management. You can download it from itellyou.cn.

Connection

You can directly use vs to connect to these two databases. Connect to localdb

 

 

DB First, Model First

  

DB First adopts the common database First approach, which is common and stable. The next step is complete.

Model First draws Model diagrams in VS to generate databases and objects, which makes it inconvenient to control databases.

These two will generate edmx files (xml), including SSDL (data definition), CSDL (class definition), CS Mapping (data class ing)

All tables are not displayed in the edmx Model View. When the relationship between the two tables is multiple-to-many, the relationship table is represented by a multi-to-many line.

In Model Browser, you can view non-table information such as stored procedures and views.

 

CodeFirst

In EF7, Only Code Only indicates the importance of Code First. In use, I also recommend small and medium-sized projects. After all, the development efficiency has improved a little bit.

 

Create POCO

    public class App    {        public int Id { get; set; }        public string Name { get; set; }        public virtual ICollection<AppData> AppDatas { get; set; }    }    public class AppData    {        public int Id { get; set; }        public string Name { get; set; }        public string Value { get; set; }        public virtual App App { get; set; }    }

Create DbContext

Public class AppContext: DbContext {public AppContext (): base ("AppDb") // AppDb database name {} public DbSet <App> Apps {get; set ;} public DbSet <AppData> AppDatas {get; set ;}}

File structure:

App. config

<Configuration> <configSections> <! -- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink? LinkID = 237468 --> <section name = "entityFramework" type = "System. data. entity. internal. configFile. entityFrameworkSection, EntityFramework, Version = 6.0.0.0, Culture = neutral, publicKeyToken = b77a5c561934e089 "requirePermission =" false "/> </configSections> <startup> <supportedRuntime version =" v4.0 "sku = ". NETFramework, Version = v4.5 "/> </startup> <entityFramework> <defaconnectionfactory type =" System. data. entity. infrastructure. localDbConnectionFactory, EntityFramework "> <parameters> <parameter value =" mssqllocaldb "/> </parameters> </defaultonfactory> <providers> <provider invariantName =" System. data. sqlClient "type =" System. data. entity. sqlServer. sqlProviderServices, EntityFramework. sqlServer "/> </providers> </entityFramework> </configuration>App. Config

 

Main Method

Static void Main (string [] args) {using (var ctx = new AppContext () {var app = new App () {Name = ""}; var data = new [] {new AppData () {Name = "latest blog", Value = "XX", App = app}, new AppData () {Name = "48-hour reading ranking", Value = "YY", App = app }}; ctx. apps. add (app); ctx. appDatas. addRange (data); ctx. saveChanges ();}}

Connect to the database and view the database.

        DbContext, DbSet

In EF, DbContext is equivalent to a database, while DbSet is equivalent to a data table or view.

 

 

Data Migration

When the business changes, the POCO class needs to change and the table needs to change.

EF data migration is carried out through NuGet.

Open the Package Manager Console and type the "get-help EntityFramework" command to obtain related help information.

Enable-Migrations [-Force]

Add-Migration

Update-Database

Get-Migrations

 

 

For example, add a Title attribute.

    public class App    {        public int Id { get; set; }        public string Name { get; set; }        public string Title { get; set; }  //add prop          public virtual ICollection<AppData> AppDatas { get; set; }    }

 

Start migration

File structure

 

Generate changes

 

If it is too troublesome, you can use the following methods:

Public class AppContext: DbContext {public AppContext (): base ("AppDb") // AppDb Database name, which can also be replaced with the connection string {Database. setInitializer (new DropCreateDatabaseIfModelChanges <AppContext> ();} public DbSet <App> Apps {get; set;} public DbSet <AppData> AppDatas {get; set ;}}

 

CRUD example:

Using (var ctx = new AppContext () {// crud # region create var app = new App () {Name = ""}; var data = new [] {new AppData () {Name = "latest blog", Value = "XX", App = app}, new AppData () {Name = "48-hour reading ranking", Value = "YY", App = app }}; ctx. apps. add (app); ctx. appDatas. addRange (data); ctx. saveChanges (); # endregion # region update app. name = "Never, C"; ctx. saveChanges (); // or ctx. apps. addOrUpdate (app); # endregion # region read app = ctx. apps. firstOrDefault (o => o. name = "blog"); Console. writeLine (app); # endregion # region delete ctx. apps. remove (app); # endregion}EF CRUD




Transaction Management

For An ORM framework, it is necessary to support transaction operations.

Each SaveChanges operation is a transaction operation. You only need to call this method after all the changes are completed.

If you do not want to, you can manually start the transaction code:

DbConnection con = (IObjectContextAdapter) ctx). ObjectContext. Connection;
Con. Open ();
Using (var tran = con. BeginTransaction ())
{
// Here is the code in the transaction

Tran. Commit ();
}
Con. Close ();

 

The above is for a DbContext, that is, when a database is involved in operations involving multiple databases, it is more reliable to use distributed transaction operations.

The use of Distributed Transaction processing requires support from the Windows system. Therefore, we need to enable the system's MSDTC Service.

 

Download Code: EFTest.zip

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.