[ASP. NET MVC]:-EF Framework Learning Notes

Source: Internet
Author: User

1. EF (Entity Framework)
Entity Framework EF is a set of technologies in ADO that support the development of data-oriented software applications and is an ORM framework for Microsoft.

2. What is ORM?
ORM refers to the mutual transformation between object-oriented object model and data structure of relational database.
(table entities are converted to each other between tables)
There are many ORM frameworks, and the EF framework is one of the ORM frameworks, and it is the framework that implements the ORM idea.

O=> Table Entity
M=> Mapping relationships
r=> database. Table

3. Create EF, add-new Item-ado.net Entity Data Model
<configuration>
<!--must follow the configuration and add
<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=5.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "requirePermission=" false "/>
</configSections>
<entityFramework>
<defaultconnectionfactory type= "System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >
<parameters>
<parameter value= "v11.0"/>
</parameters>
</defaultConnectionFactory>
</entityFramework>
<!--database connection string, using EF must add Providername= "System.Data.EntityClient"-
<connectionStrings>
<add name= "Modelcontainer" connectionstring= "METADATA=RES://*/MODEL.CSDL|RES://*/MODEL.SSDL|RES://*/MODEL.MSL ;p rovider=system.data.sqlclient;provider connection String=&quot;data source=.; Initial catalog=hx_shop;persist security Info=true;user id=sa;password=123456; Multipleactiveresultsets=true; app=entityframework&quot; "providername=" System.Data.EntityClient "/>
</connectionStrings>
</configuration>

4. Getting started with a simple EF

  Create EF context  Model.modelcontainer db = new Model.modelcontainer ();  The only example  UserInfo info = new UserInfo () in the following thread-in-the-wire instance;  Info. Name = "Zhang San";  Db. Userinfo.add (info); Add Data  db. SaveChanges (); Finally, you must SaveChanges () to save and map the entity of the State back to the database.  //info. Id = 1; To modify or delete an operation, you must have a primary key.  //db. Entry<t> (entity). state = entitystate.added;  Add  //db. Entry<t> (entity). state = entitystate.modified;  Modify the  //db. Entry<t> (entity). state = entitystate.deleted;  Delete


4.1 EF4.0 and EF5.0 of the different wording.
View Code

Public T addentity (t entity) {//ef4.0 add entity//db. Createobjectset<t> ().    AddObject (entity); EF5.0 the notation of DB. Entry<t> (entity).    state = entitystate.added; The following syntax is unified DB.    SaveChanges (); return entity;} public bool Updateentity (T entity) {//ef4.0//db. Createobjectset<t> ().    Addach (entity); Db.    Objectstatemanager.changeobjectstate (entity, entitystate.modified); EF5.0 the notation of DB. Set<t> ().    Attach (entity); Db. Entry<t> (entity).    state = entitystate.modified; Return DB. SaveChanges () > 0; }public BOOL Deleteentity (T entity) {//ef4.0 notation//db. Createobjectset<t> ().   Addach (entity); Db.   Objectstatemanager.changeobjectstate (entity, entitystate.deleted); EF5.0 the notation of DB. Set<t> ().   Attach (entity); Db. Entry<t> (entity).   state = entitystate.deleted; Return DB. SaveChanges () > 0;} Public iqueryable<t> loadentities (func<t, bool> wherelambda) {//ef4.0 the notation//return db. Createobjectset<t> (). WHere<t> (WHERELAMBDA).    AsQueryable (); The EF5.0 is written in return DB. Set<t> (). Where<t> (WHERELAMBDA). AsQueryable ();} Execute SQL statement//ef4.0 public int excutesql (String sql, params objectparameter[] parameters) {return dbcontext.executefuncti On (sql, parameters);} EF5.0 public int ExecuteSQL (String sql, params system.data.sqlclient.sqlparameter[] pars) {return Dbcontext.databa Se. Executesqlcommand (SQL, pars);}


5, increase the deletion of the search practice

public class baserepository<t> where T:class,new () {private DbContext DbContext {get            {return dbcontextfactory.createdbcontext ();//Create a unique instance.         }}//Simple query public iqueryable<t> loadentities (expression<func<t, bool>> Wherelambda) {return dbcontext.set<t> (). Where (WHERELAMBDA).        AsQueryable (); }//Paging query * * * public iqueryable<t> loadpageentities<s> (int pageSize, int. PageIndex, out int total             Count, Expression<func<t, bool>> Wherelambda, bool Isasc, expression<func<t, s>>) { iqueryable<t> result = dbcontext.set<t> (). Where (WHERELAMBDA).            AsQueryable (); TotalCount = result.  Count (); Returns the total number of record bars if (ISASC) {result = result. The (by). Skip (PageSize * (pageIndex-1)).     Take (PageSize)               .            AsQueryable (); } else {result = result. OrderByDescending (to be). Skip (PageSize * (pageIndex-1)). Take (pageSize).            AsQueryable ();        } return result; } public T Add (t entity) {dbcontext.set<t> ().            ADD (entity);        return entity; The public bool Detele (T entity) {Dbcontext.entry (entity).            state = entitystate.deleted;        return true; public bool Update (T entity) {Dbcontext.entry (entity).            state = entitystate.modified;        return true; }    }


6. EF supports database first, model first, and code only three development modes
Database First: Generate models from databases, with databases, and models based on databases.
Model First: A database-generated entity Object model that is designed to create a database.
Code Only:code First
Http://www.cnblogs.com/fly_dragon/archive/2011/02/22/1961730.html
Http://www.cnblogs.com/fcsh820/archive/2010/11/01/1866356.html

7. Delay Loading mechanism
Off-line Collection <IQueryable>
The deferred loading mechanism will not load the data (access the database) until this collection is used.

How to avoid the delay loading mechanism to query the database multiple times?
Use the memory-type collection tolist () list<t>

8. Linq, lambda-expression learning
http://www.cnblogs.com/han1982/tag/LINQ/


Note:
1, using the EF framework, the EF table must have a primary key, no error.
2, Error: The validation of one or more entities failed. Entity attribute assignment problem.
3, EF performance is poor, more than ADO to generate SQL script, the implementation of complex query generated SQL script. Advantages outweigh the disadvantages.
3, EF context Management, ensure that instances within the thread are unique.
A memory space inside the thread
Callcontext.setdata ("DbContext")//settings
CallContext.GetData ("DbContext")//Get instance
httpcontext.item["Key" is also implemented through CallContext.

    <summary>///    guarantee the context of EF. Within-thread instance unique, request one instance at a time,///    </summary> public    static class Dbcontextfactory    {public        static DbContext Createdbcontext ()        {            //thread within instance unique            DbContext db = (DbContext) httpcontext.current.items["DbContext "];            if (db = = null)            {                db = new Model.modelcontainer ();                HTTPCONTEXT.CURRENT.ITEMS.ADD ("DbContext", db);            }            return db;        }    }

[ASP. NET MVC]:-EF Framework Learning Notes

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.