Entity Framework Code First database connection

Source: Internet
Author: User
Tags connectionstrings

Reference page:

Http://www.yuanjiaocheng.net/entity/entitytypes.html

Http://www.yuanjiaocheng.net/entity/entity-relations.html

Http://www.yuanjiaocheng.net/entity/entity-lifecycle.html

Http://www.yuanjiaocheng.net/entity/code-first.html

Http://www.yuanjiaocheng.net/entity/mode-first.html

1. Installing the Entity Framework

Use NuGet to install the Entity Framework Package: tools, library Package Manager, and Package Manager console, execute the following statement:

Pm> Install-package EntityFramework
2. Entity Framework Database Connection Configuration

After the Entity Framework is installed, the App. Config file is added automatically. The defaultconnectionfactory of the Entity Framework is configured in this file, and the connection after modifying the database connection string is as follows:

<?xml version="1.0"encoding="Utf-8"?><configuration> <configSections> <section name="EntityFramework"Type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=4.4.0.0, culture= Neutral, publickeytoken=b77a5c561934e089"requirepermission="false"/> </configSections> <entityFramework> <defaultconnectionfactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"> <parameters> <parameter value="Data source= (local); Database=portal; User Id=sa; password=; Multipleactiveresultsets=true"/> </parameters> </defaultConnectionFactory> </entityFramework></configuration>

After you have set up defaultconnectionfactory for the Entity Framework above, using the Entity Framework to connect to the database does not need to be set elsewhere, entity The framework also does not need to specify a database connection.

Entity Framework Connection database In addition to the above, you can also modify the app. Config as follows by configuring the commonly used connectionstrings:

<?xml version="1.0" encoding="utf-8"?>< configuration>  <connectionStrings>    <add name="portalcontext" connectionstring="Data source= (local); Database=portal; User Id=sa; password=; Multipleactiveresultsets=true"      providerName="  System.Data.SqlClient" />  </connectionStrings></configuration>
3. Entity Framework DbContext Connection Database

New class file PortalContext.cs, specific code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Data.Entity;namespaceportal{ Public classPortalcontext:dbcontext {StaticPortalcontext () {Database.setinitializer<PortalContext> (NULL); //Database.setinitializer (New createdatabaseifnotexists<portalcontext> ()); //Database.setinitializer (New dropcreatedatabasealways<portalcontext> ()); //Database.setinitializer (New dropcreatedatabaseifmodelchanges<portalcontext> ());        }         PublicPortalcontext ():Base("Name=portalcontext")        {        }        protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {}}}

In PortalContext.cs, static constructors and constructors for classes are used. Where you set the initialization of the database in the static constructor and specify the connectionstring of app. Config in the constructor.

3.1 Entity Framework Database initialization mode

The Entity framework specifies the type of database initialization required by Database.setinitializer, and there are 3 types of databases Database.setinitializer can specify:

  1>. Createdatabaseifnotexists

Createdatabaseifnotexists is the default way for Database.setinitializer to specify a database, which is used to automatically create a database when the database does not exist. Because this is the default way, you can specify it without any code, but you can also use code to specify it explicitly.

Database.setinitializer (new createdatabaseifnotexists<portalcontext> ());

  2>. Dropcreatedatabasewhenmodelchanges

Dropcreatedatabasewhenmodelchanges is used to delete the original database when the data model changes, and then create a new database.

Database.setinitializer (new dropcreatedatabaseifmodelchanges<portalcontext> ());

  3>. Dropcreatedatabasealways

Dropcreatedatabasealways is used to delete the original database each time before creating a new database, regardless of whether the data model has changed.

Database.setinitializer (new dropcreatedatabasealways<portalcontext> ());

However, in many cases, we hope that even when the Entity Framework code first does not match the database, the Entity Framework code first reports a database connection error and does not want any delete creation operations on the database. The Entity Framework Code first provides the shutdown of the database initialization operation:

Database.setinitializer<portalcontext> (null);
Some settings for the 3.2 Entity Framework Code First Connection database

When you actually use the Entity Framework code first to manipulate a database, you typically do some database operation settings for the Entity Framework code first in the class that inherits DbContext.

  1>. Disable lazy loading (lazy Loading)

In the two entity classes in which a reference relationship exists, an instance of one class can get one or more instances of another class corresponding to it through an association relationship. In this acquisition, the Entity Framework Code first provides the default lazy load feature. An instance of a class that, when it is necessary to use an instance of another class, can read directly the associated property defined in the class, and the Entity framework will automatically go to the database to read the records that are required to return. Of course this is the benefit of lazy loading, and there are some bad places to delay loading as well. When the Entity Framework reads the associated records through lazy loading, it is possible to execute too many SQL statements that are inconsistent with what is actually expected, thus affecting the efficiency of code execution.

Set the default disable lazy loading, which is displayed when the Entity Framework is required to read the associated data records.

 Public portalcontext ()     Base ("name=portalcontext") {    //  Disable lazy loading this      false;}

  2>. Disabling cascade deletion of relational data

When the primary table record is deleted, the records associated with the table are automatically deleted when the data record exists for the associated relationship. This is a feature that is mostly present in relational databases, including MS SQL Server. However, in an actual project, you often do not want to use this cascade delete feature and write code to delete the associated records when you need to delete them.

The Entity Framework Code first sets the Cascade Delete feature to disable the associated data by default:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {    //  Disable a pair of cascade deletions    Modelbuilder.conventions.remove<onetomanycascadedeleteconvention>();     // disabling multiple-to-multi-cascade deletions    Modelbuilder.conventions.remove<manytomanycascadedeleteconvention>();}

  3>. Disable default table name plural form

When the Entity Framework Code first generates a data table based on the class name, the resulting data table table name is the plural form of the class name.

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {    //  Disable default table name plural form    Modelbuilder.conventions.remove<pluralizingtablenameconvention>();}

Finally, attach the complete code of PortalContext.cs in this essay:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Data.Entity;usingSystem.Data.Entity.ModelConfiguration.Conventions;namespaceportal{ Public classPortalcontext:dbcontext {StaticPortalcontext () {Database.setinitializer<PortalContext> (NULL); }         PublicPortalcontext ():Base("Name=portalcontext")        {            //Disable Lazy loading             This. configuration.lazyloadingenabled =false; }        protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {//Disable default table name plural formModelbuilder.conventions.remove<pluralizingtablenameconvention>(); //disabling a pair of cascade deletionsModelbuilder.conventions.remove<onetomanycascadedeleteconvention>(); //disabling multiple-to-multi-cascade deletionsModelbuilder.conventions.remove<manytomanycascadedeleteconvention>(); }    }}

Entity Framework Code First database connection

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.