Little white Learn to do project (2) _ Implement code First design database using EntityFramework (2)

Source: Internet
Author: User

Welcome to our humble abode again.

Yesterday, we have successfully mapped our user class to the database. *★,°*:.☆\ ( ̄▽ ̄)/$:*. °★*

But we also see in the database that all the columns in the database are mapped by default categories, and today we are going to modify the mapping rules for these genera.

Code first has two ways to configure database mapping, one is to use the data attribute dataannotation, and the other is the fluent API.

The way dataannotation is configured requires you to add the configuration tags associated with the database mappings to the attributes in the classes and classes that define the entity and value objects.

For example, our user class, according to code First's default rule, indicates that the user should be called, but we want to set the table name to UserInfo, so how can we use Dataannotation to let code first configure the name of the data table according to our requirements?

A simple mess:

[System.ComponentModel.DataAnnotations.Schema.Table ("UserInfo")]     Public classUser { Public intUserID {Get;Set; }  Public stringNick {Get;Set; }  Public stringAddress {Get;Set; }  Public stringLoginName {Get;Set; }  Public stringPassword {Get;Set; }  Public stringPhoneNumber {Get;Set; }  Public stringEmail {Get;Set; } }
User

Another way to configure this is to use the fluent Api,code first fluent API as a way to define the database configuration in DbContext. To use the fluent API, you must overload the Onmodelcreating method in your custom class that inherits from DbContext. Configure the database mappings for each class in your DbContext by ModelBuilder This object's entity<> generic method. The sample code is as follows:

     Public classBlogcontext:dbcontext { PublicBlogcontext ():Base("Name=blog")        { }         PublicDbset<user> Users {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {modelbuilder.entity<User> (). ToTable ("UserInfo"); }    }
Blogcontext

Then in the actual project, we adopt which kind of configuration is freely chosen by everyone, this article uses the suggestion of Brother Liu to introduce is the fluent API setting way. (In fact, I was studying in (-__-)b)

The return value of the ModelBuilder entity<user> method is the Entitytypeconfiguration<user> class, which can be passed through its property method, The properties of the specified column in the data table are set by the LAMDA expression.

     Public classBlogcontext:dbcontext { PublicBlogcontext ():Base("Name=blog")        { }         PublicDbset<user> Users {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {modelbuilder.entity<User> (). Property (s = = S.password). IsRequired (). Hasmaxlength ( -); Modelbuilder.entity<User> (). Property (s = = S.loginname). IsRequired (). Hasmaxlength ( -); Modelbuilder.entity<User> (). Property (s = = S.phonenumber). Hasmaxlength ( -); Modelbuilder.entity<User> (). Property (s = = S.email). Hasmaxlength ( -); }    }
Blogcontext

But for our user class, we have to make a unique restriction on loginname,phonenumber,email in addition to the UserID. (This is not the same as I think).

Before we do that, we will first map our currently modified columns to the database.

Do not know when people run the test when the error. In fact, through yesterday's project, our database already has the database Xyy.blog, and this time the user table in the submission of the qualification and the original inconsistency, so will be error.

In fact, only in the development phase, we will have to modify the table in the database column properties of this operation, we can use code first provided by the database class Setinitializer method to set how code first according to the fluent The API Database mapping configuration initializes the database.

The parameters of the Setinitializer method can make the following three generic classes of objects:

CREATEDATABASEIFNOTEXISTS<>: A new database is created based on the database connection configuration only when there is no database. This configuration is primarily used for production environments, because you cannot delete the database you are currently using, which can result in loss of important data. You need to have your implementers take the database script corresponding to the fluent API configuration to update the database.

Dropcreatedatabaseifmodelchanges<>: As long as the database mapping of the fluent API configuration changes or the model L of the program changes, the previous database is deleted and the database is re-established according to the new configuration. This approach is more appropriate for the development phase and can reduce the workload for developers.

Dropcreatedatabasealways<>: Regardless of whether the database mapping or model has changed, each time it is re-deleted and the database is rebuilt according to the configuration. This approach can be applied to a number of special cases, such as removing all test data after each test and inserting some basic data before the test begins.

Well, in the development phase, we have to make changes to our database based on requirements, so here we use the generic class dropcreatedatabasealways<>.

In fact, we can directly use the test class, console and other portals directly

Database.setinitializer (New dropcreatedatabasealways<blogcontext> ());

Set at the same time, dbContent.Database.Initialize (true);

But this is not recommended, the best way to use it is as follows

     Public class Dropcreateorderdatabasewithseedvaluealways:dropcreatedatabasealways<blogcontext>    {    }
seedvaluealways

Internal implementation, first empty, and temporarily do not affect our program, will be used again later to this custom class.

Let's test the actual test class code as follows:

[TestClass] Public classTest {[TestMethod] Public voidMyTest () {System.Data.Entity.Database.SetInitializer (Newdropcreateorderdatabasewithseedvaluealways ()); Blogcontext dbcontent=NewBlogcontext (); DbContent.Database.Initialize (true); varBlogcontext =NewBlogcontext (); //var blogcontext = new Acontext (); //var user = new User () {UserID = 1, LoginName = "888888", Password = "53523113"}; //blogContext.Users.Add (user);            varRR =blogcontext.savechanges (); //new Blogcontext (). SaveChanges ()        }    }
Test

After successful operation, we compare:

As you can see clearly, our settings are effective.

Originally wanted to set the unique constraints here, but the middle of the implementation and I imagined not the same, there is no way, this section is here, tomorrow we mainly explain the unique constraints and initialization of data knowledge.

Little white Learn to do project (2) _ Implement code First design database using EntityFramework (2)

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.