MVC database Learning (1) -- automatically update a database using the Entity Framework

Source: Internet
Author: User

In any framework, database usage is a key because most of the data we use is stored in the database. ASP. net mvc provides excellent support for databases, especially when we are developing, we can use the Entity Framework.CodeCode-first is preferred.

The so-called code priority should be discussed with model priority or database priority. Simply put, model first means that we must first design the model and then generate the database structure through the model. Database first means that we design the model on an existing database. This understanding is very crude, but the discussion about the database requires a deep basic knowledge as a reserve. In view of my own level, it is inconvenient to start here. Code priority is the performance of MVC "convention is better than configuration. The so-called "conventions are better than configurations" is a concept widely spread in Ruby. The essential meaning is that we can apply the accumulated experience to the framework, so that we do not need to configure each item for future development. In code-first mode, even if we haven't created our database, we can still create our object, that is, model. During the creation process, there is no need to consider the complex relationship between objects in the database, and no need to add any labels on the data persistence layer, which plays a very important role in the Entity Framework's primary key recognition behavior.

To use this development method, we need to understand the infrastructure provided by ASP. net mvc. The base frame is a very powerful tool that can be used for applications.ProgramCrud (create, read, update, delete) to generate the required sample code. The Base Frame generates the controller and the associated view of the controller according to the definition of the model. In short, the base frame can generate a default template for us, and then we can modify it as needed.

Because of the base frame, the use of the physical framework is more powerful. Object framework, as its name implies, is an object link ing framework. The Entity Framework is really smart. It knows that the attribute in our model is a key value, even if we didn't specifically remind you. Well, we have already reminded you that our key values are generally named like this: xxid, where XX is the name of the model. The entity framework assumes that this attribute is the key value, and assigned to the auto-incrementing key column corresponding to SQL Server. These assumptions are conventions. As long as the attribute names under this framework comply with these conventions, we can enjoy this convenience. Of course, EF has its conventions on Foreign keys and database names.

Even if our database is simulated, we need to create it. To create a simulated database, we need to assign a class from the dbcontext class of EF to access the database:

  Public   class   storecontext: dbcontext {  Public  dbset 
  
    Users {
    Get ; 
    set  
   ;} 
    Public  dbset 
   
     categories {
     Get ; 
     set  
    ;} 
     Public  dbset 
    
      comments {
      Get ; 
      set  
     ;} 
      Public  dbset 
     
       logs {
       Get ; 
       set  
      ;} 
     
    
   
  

This derived class has one or more fields of the dbset <t> type. T is a generic type, indicating the object we want to save permanently.
Next, we only need to update it and use it in combination with LINQ to perform various database operations, such as the following query:

 
User user = (FromUInStoredb. UsersWhereU. Name. tolower () =User. Identity. Name. tolower ()SelectU). firstordefault ();

Dbcontext, as its name implies, is the data context. In actual programming, the model is sometimes modified, but what about the database? The database will not be automatically updated by itself, so this error will occur at this time:

The model that supports the "storecontext" context has been changed after the database is created. Please consider using code first to migrate and update the database
There are two solutions to this problem: re-create the database and modify the database.

Manual operations are required to modify the database. re-creation of the database can be performed automatically in some way. Generally, our model will not be modified during the official release. This happens only during testing. Therefore, during development, the first method is the best.

To enable automatic database creation, we need a new class:

 
 Public ClassUserintializer: dropcreatedatabaseifmodelchanges <storecontext>{Protected Override VoidSeed (storecontext context ){Base. Seed (context );}}

The re-creation of the database will make all the previous data disappear, but if we want to retain the original value in a table when re-creating the database, instead of entering it manually, you can write in seed as follows:

VaRUsers =NewList <users>{NewUser {userid=123, Name="XI Jun",}; Users. foreach (u=> Context. Users. Add (u ));

After the class is created, the next thing we need to do is to automatically rebuild the database when our application starts running. To implement this function, we must configure it in the global. ascx file under the project root directory.
Global. the ascx file defines the application main class used by the current project. It contains an application_start () event processor, when our application runs for the first time, it will trigger events in it.

You must add the following code to the file:

System. Data. entity. database. setinitializer <storecontext> (NewUserintializer ());

The full name of the database namespace must be specified here. Even if we import its namespace correctly, it still does not work, because this method is a static method.

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.