Http://www.cnblogs.com/qouoww/archive/2012/01/05/2313231.html (excellent introduction blog)
Http://weblogs.asp.net/manavi/archive/2011/01/03/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines.aspx
Http://www.cnblogs.com/wlflovenet/archive/2011/08/08.html
Http://www.cnblogs.com/LingzhiSun/
Http://code.msdn.microsoft.com/EFProviderWrappers-c0b88f32 about processing with Level 2 Cache and logging SQL logs
Http://www.codeproject.com/Articles/435142/Entity-Framework-Second-Level-Caching-with-DbConte Level 2 Cache and records SQL logsCodeExample
Http://www.cnblogs.com/LingzhiSun/archive/2011/05/24/EFPowerTool_1.html entityfreamwork gadgets, this person's blog is pretty good
Http://www.dotblogs.com.tw/code6421/archive/2010/09/02/17526.aspx update the specified field does not need to be queried first
Http://www.cnblogs.com/dudu/archive/2011/04/06/2006709.html update the specified field does not need to be queried first
_ The above is more effective. _ The following is average.
Link http://blog.sina.com.cn/s/blog_8a5695250100ti25.html
1. directly execute SQL statements
In general, EF does not need to write SQL statements, but in some cases, for example, it is not satisfied with the generated SQL statements to be optimized or it is necessary to write abnormal SQL statements during report statistics.
In this case, the vulnerabilities of Using ORM are revealed in batch operations. However, as an excellent ORM framework, EF provides three methods to support the original SQL.
1.Dbset. sqlquery query with tracking status
2.Dbdatabase. sqlquery queries with no trace status
3.Dbdatabase. sqlcommand directly executes SQL statements, which are generally used for batch addition, deletion, and modification.
Next let's take a look at the usage
Add a method to the public resource library in the previous article
PublicVirtualIenumerable<Tentity>Getwithrawsql (StringQuery,ParamsObject [] Parameters ){Return Dbset. sqlquery (query, parameters );}PublicVirtualIenumerable<Tentity>Getwhithdbsql (StringQuery,ParamsObject [] Parameters ){ReturnContext. database. sqlquery<Tentity> (Query, parameters );}
The difference between the first and the second is described through comparison ~~
Execute these two methods in the course controller.
VaR Query="Select * from course where courseid = @ P0" ; Course course= Unitofwork. courserepository. getwithrawsql (query, ID). Single (); entitystate state= Unitofwork. getstate (course );StringName= Course. Department. Name; course coursetwo= Unitofwork. courserepository. getwhithdbsql (query, ID). Single (); entitystate statetwo= Unitofwork. getstate (coursetwo );StringNametwo=Coursetwo. Department. Name;
Result After execution
1. First, check that the first State is unchanged. That is to say, he adds the context and has a trace state.
And the following can be read smoothlyCourse. Department. Name, that is, the navigation attribute can be read.
2. Check that the second State is that detached is not added
No trace status in context Context
Therefore, the following error will be reported when reading the content of the navigation attribute ~~
3. Let's talk about it again.
Dbdatabase. sqlcommand: This is relatively simple to add, delete, and use. This is good. Here is an example of batch update ~
If you need to update all course credits to N, it will be inconvenient to use the ORM framework in this batch operation. In this case, we can use this to directly execute SQL statements.
This business belongs to the course, so it inherits the general resource library Class Code as follows:
Using System;Using Contosouniversity. models;Namespace Contosouniversity. Dal {PublicClassCourserepository: genericrepository<Course> { Public Courserepository (schoolcontext context ):Base (Context ){}PublicIntUpdatecoursecredits (Int Multiplier ){ReturnContext. database. executesqlcommand ("Update course set credits = credits * {0}" , Multiplier );}}}
Modify the previous
Unitofwork class
Private Courserepository;Public Courserepository {Get { If(This. Courserepository=Null ){This. Courserepository=New Courserepository (context );}Return }}
The Controller is as follows:
PublicActionresult updatecoursecredits (Int?Multiplier ){If(Multiplier! =Null) {Viewbag. rowsaffected=Unitofwork. courserepository. updatecoursecredits (multiplier. Value );}ReturnView ();}
Add a view ~~
Running result Diagram
Ii. No trace Query
What is tracing query enabled for EF by default? Let's take a look at the following code.
Department duplicatedepartment= DB. Orders ments. Where (d=>D. instructorid= Department. instructorid). firstordefault (); duplicatedepartment. Name="Wuhawuha" ; bool isupdate = dB. entry Department > (duplicatedepartment ). property (P => P. name ). ismodified; // whether to modify string now = dB. entry Department > (duplicatedepartment ). property (P => P. Name). currentvalue; // Current ValueStringBefore=DB. Entry<Department>(Duplicatedepartment). Property (P=>P. Name). originalvalue; // previous value
We first randomly find out a department information and modify his name. This is what we will use the above information to get the current value. The previous value. This is what we do. Let's see what we didn't do.
It is easy to add a trace-free configuration during query.Asnotracking ()You can. After adding the parameter, we can see that it has changed but isupdate is still false. In addition, an exception is thrown when the previous value is obtained.
In general, we do not need to track these statuses. we can remove the trace query during the query to improve the performance ~ I used to think that removing this will affect the use of navigation attributes, but it will not be affected after testing ~
This tracing query also brings about another problem. See the figure below.
This is because an error is reported if you add a statement before the modification to query the modification and then modify it.An object with the same key already exists in objectstatemanager. Objectstatemanager cannot trace multiple objects with the same key.
When this error occurs, addAsnotracking ()You can. At present, I do not like tracing when using EF ~~ Like to addAsnotracking ()
3. Use proxy
After understanding the orm framework, we know that the navigation attribute uses the proxy mode, which is also related to the navigation attribute. Disabling proxy can speed up serialization.
The code for disabling proxy adds the following code to the class that inherits dbcontext
PublicSchoolcontext ()
{This. Configuration. proxycreationenabled=False;}
The following shows the differences between agent and agent.
Our administrator is a navigation attribute. We can see a long string of numbers and letters. When we access this administrator attribute below, we will get the Administrator attribute through delayed loading.
Let's look at the figure when the proxy is disabled.
If all of our navigation attributes are null, the navigation attributes cannot be obtained correctly.
Iv. Automatic Detection
Dbset. Find
Dbset. Local
Dbset. Remove
Dbset. Add
Dbset. Attach
Dbcontext. savechanges
Dbcontext. getvalidationerrors
Dbcontext. Entry
Dbchangetracker. Entries
In the preceding method, the automatic detection function is called. This feature is enabled by default. we can disable this feature during batch operations to improve performance. For example:
Using(VAR Context=New Unicornscontext ()){Try {Context. configuration. autodetectchangesenabled =False ;//Make calls callin a loop Foreach(VAR unicornIn Myunicorns) {context. Unicorns. Add (UNICORN );}}Finally {Context. configuration. autodetectchangesenabled =True ;}}
Http://kb.cnblogs.com/page/98712/
Http://blogs.msdn.com/ B /adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx official
Http://blogs.msdn.com/ B /adonet/archive/2011/02/04/using-dbcontext-in-ef-feature-ctp5-part-10-raw-sql-queries.aspx
Http://www.cnblogs.com/haogj/archive/2011/05/09/2040196.html
Http://kb.cnblogs.com/page/127199/ EF FAQ
Reprinted from: http://www.cnblogs.com/shanyou/archive/2011/07/17/2108953.html
To support the design-centric development process, EF4 also supports code-centric development, code-first Development supports a more elegant development process, which allows you:
- Develop without using the designer or defining an XML ing file.
- You can write a simple model object poco (plain old classes) without the need for a base class.
- The database persistence layer does not require any configuration through "conventions are better than configurations"
- You can also overwrite "conventions are better than configurations" and use Smooth APIs to completely customize the persistence layer ing.
After using the code first mode, you can say that you no longer need the data model automatically generated by the. edmx system in your project.
ChineseArticle:
EF framework step by step (3)-code-firstef framework step by step (7)-code first dataannotations (1) EF framework step by step (8) -Code first dataannotations (2) EF framework step by step (9)-code first fluent API
Entity Framework 4.1 code first (1)
Entity Framework 4.1 code first (2)
Entity Framework 4.1 code first (3)
Entity Framework 4.1 code first (4)
Entity Framework 4.1 code first (5)
Endless. Net 4.0 (9)-code first of ADO. NET Entity Framework 4.1
EF code-first custom table ing
Entity Framework code first user's gospel-one of EF power tool's usage notes
Efmvc-ASP. net mvc 3 and Entity Framework 4.1 code first Project Introduction
Use EF code first and ASP. NET mvc3 for class-level model verification
Control entityframework4.1 code-first by yourself to gradually eliminate the strange phenomenon of EF
You can control entityframework4.1 code-first by yourself. It has multiple powerful loading methods for EF.
Indecisive about Entity Framework
Collection of Entity Framework Problems
Summary of Entity Framework queries
In-depth analysis of Entity Framework
Mvc3 + ef4.1 Learning Series
English article:
The repository pattern with EF code first & dependeny injection in ASP. NET mvc3
Entity Framework Code-first, odata & Windows Phone Client
An open source ASP. net mvc 3 blog engine
Http://weblog.codeplex.com/