Entity Framework Code First database connection

Source: Internet
Author: User
Tags connectionstrings

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:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Data.Entity; namespace portal{public    class Portalcontext:dbcontext    {        static portalcontext ()        {            Database.setinitializer<portalcontext> (null);            Database.setinitializer (New createdatabaseifnotexists<portalcontext> ());            Database.setinitializer (New dropcreatedatabasealways<portalcontext> ());            Database.setinitializer (New dropcreatedatabaseifmodelchanges<portalcontext> ());        }        Public Portalcontext ()            : Base ("Name=portalcontext")        {        }        protected override void Onmodelcreating (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    . configuration.lazyloadingenabled = 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> ();    Disable multiple-to-multi-cascade delete    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:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Data.Entity;using        System.data.entity.modelconfiguration.conventions;namespace portal{public class Portalcontext:dbcontext {        Static Portalcontext () {database.setinitializer<portalcontext> (null); } public Portalcontext (): Base ("Name=portalcontext") {//disable lazy loading this.        configuration.lazyloadingenabled = false;            } protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {//disable default table name plural form            Modelbuilder.conventions.remove<pluralizingtablenameconvention> ();            Disable a pair of cascade deletions modelbuilder.conventions.remove<onetomanycascadedeleteconvention> ();        Disable multiple-to-multi-cascade delete modelbuilder.conventions.remove<manytomanycascadedeleteconvention> (); }    }}

Original address: http://www.cnblogs.com/libingql/p/3351275.html

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.