The previous three sheets are basic, and if you do not consider the architectural problems, do the general applet to be sufficient. The basic additions and deletions have also been changed. But as learning is clearly not enough. Through the previous three chapters of the study, there is no way to find out what the problem of writing, there is no tedious? Some might say that the previous three articles add up to dozens of lines where the code is cumbersome. Oh, is not that EF is very powerful. But in fact, according to the previous wording is more cumbersome, why? This is the focus of this article and then look down!!!
First look at the previous configuration class
Review our example is only two tables, then need to configure the mapping relationship when the DbContext, the onmodelcreating is configured. But if there are dozens of and more complex tables, if you put into this onmodelcreating inside to write the words will not feel too messy no reason, even the relationship has been divided.
Then we'll figure out how to make the relationship of each table be configured only in one Entity relationship configuration class.
Specific content to look down
The above content does not know that you understand no, or I say not clear, the solution is that we can create a configuration class for each entity or a common configuration class to complete the relationship mapping settings. Then let's start doing it.
1. Create a new configuration folder under Model
2. A new configuration class is also created for the two entities previously written
3, the core code came.
The above two-step dynamic mouse can be done. That's the exact code here. Let's look at the mapping class for user information first.
/// <summary> /// Blog User Information mapping class /// </summary> Public class Bloguserconfiguration:entitytypeconfiguration<bloguser> { public Bloguserconfiguration () { // Set Primary key Haskey (m = m.bloguserid); } }
It's simple! We can move the previously onmodelcreating configuration to each corresponding entity, where the core of the class is referencing the entitytypeconfiguration, so why reference it?
The following sentence is the code we wrote in the second article, and you put the mouse on the Haskey to see the reference.
Modelbuilder.entity<bloguser> (). Haskey (M = M.bloguserid);
Transfer it to the following.
Now know why to quote Entitytypeconfiguration! If we do not reference it, we cannot write the configuration in the construction method.
4, the last step, modify the DbContext inside the Onmodelcreating method to comment out the previous code. Each class is changed to a single line of code implementation.
5, complete, run your code is not also appear before the correct page.
If you do not understand what you can leave a message, but also welcome you to guide through progress.
Step by Step EF Series "4, upgrade entity and database mapping"