Complete video of the musicstore project!
Last time, we used simulated data to be sent from the Controller to the view template. Now, we start to use a real database. In this tutorial, We will guide how to use a database of SQL Server compact, which is often called SQL Ce as a database engine, SQL CE is a free, embedded, and file-based database system that is suitable for local development and use without any installation or configuration.
Note: you may need to install the SQL Server compact 4.0 database and Entity Framework separately. On my machine, both software is installed separately.
Of course, you can also use familiar SQL Server databases.
Microsoft SQL Server compact 4.0
Microsoft SQL Server compact 4.0 is a free embedded database, that is, you do not need to install the database system. Software developers can use it to build ASP. NET websites and Windows desktop applications.Program. SQL Server compact 4.0 has the following advantages: it occupies a small amount of space and supports deploying binary files in the application folder. It is easy to use Visual Studio and webmatrix for application development, and seamlessly migrate the Architecture and Data to SQL Server.
SQL Server compact 4.0 Installation File: http://www.microsoft.com/downloads/zh-cn/details.aspx? Familyid = 033cfb76-5382-44fb-bc7e-b3c8174832e2 & displaylang = ZH-CN
However, you can continue to use the original SQL server without using this database. On my machine, I cannot directly use the server resource manager to view SQL Ce 4 data. If you use the original SQL server, this problem will not occur.
ADO. NET Entity Framework 4.1
What are new features of EF 4.1?
1. First of all, it is dbcontext API, which is a simple API abstracted Based on objectcontext in previous versions and other types. It is optimized for common development scenarios and programming modes. Dbcontext can be used in three development modes: database first, model first, and code first.
2. Code first is a new development mode based on Entity Framework. It was originally only available in database first and model first. Code first, as its name implies, defines your domain model with C #/VB. NET classes, maps these classes to existing databases, or generates new database structures. Code first also supports custom configuration through data annotations or fluent APIs.
The data access here is completed using code first, which will make your data access incredibly simple.
About ADO. NET Entity Framework 4.1, I previously translated a series, address: http://www.cnblogs.com/haogj/archive/2011/05/06/2038965.html
ADO. NET Entity Framework 4.1 Installation File: http://www.microsoft.com/download/en/details.aspx? Displaylang = en & id = 8363
Use Entity Framework Code-first for data access
We will use Entity Framework (EF) included in ASP. NET mvc3 to support querying and updating data in the database. EF is a flexible object link ing API for data access. It allows developers to query and update data in the database in an object-oriented manner.
Entity Framework 4 supportsCodeThe preferred development mode, limited code allows you to create Model Objects (also known as poco, simple, old CLR objects) by writing simple classes, and then create data through classes.
Note: You need to reference the Assembly entityframework in your project. You can find this Assembly in the folder where you install the Entity Framework.
Modify our model class
We will delay database creation. before completing this task, we need to modify the model class and add the content we need.
Add artist class
Our albums will be associated with artists, so we need to add a simple class to describe artists and add a new class named artist.
NamespaceMvcmusicstore. Models
{
Public ClassArtist
{
Public IntArtistid {Get;Set;}
Public StringName {Get;Set;}
}
}
Update existing model classes
Namespace Mvcmusicstore. Models
{
Public Class Album
{
Public Int Albumid { Get ; Set ;}
Public Int Genreid { Get ; Set ;}
Public Int Artistid { Get ; Set ;}
Public String Title { Get ; Set ;}
Public Decimal Price { Get ; Set ;}
Public String Albumarturl { Get ; Set ;}
Public Genre genre { Get ; Set ;}
Public Artist { Get ; Set ;}
}
}
Then update the genre class
NamespaceMvcmusicstore. Models
{
Public ClassGenre
{
Public IntGenreid {Get;Set;}
Public StringName {Get;Set;}
Public StringDescription {Get;Set;}
PublicList <album> albums {Get;Set;}
}
}
Add the app_data folder.
This step is not necessary. If SQL Ce4 is used, it can be used to save database files. If SQL Server is used, it is not required.
We added the app_data folder in the project to save database files. app_data is an ASP.. net. and then select app_data.
Create a database connection string in Web. config
We need to add some lines to the website configuration file so that Entity Framework knows how to connect to our database and double-click the web. config file.
Volume to the end of the file, and then add a <connectionstrings> Configuration section, as shown in:
<Connectionstrings>
<AddName= "Musicstoreentities"
Connectionstring= "Data Source = | datadirectory | mvcmusicstore. SDF"
Providername= "System. Data. sqlserverce.4.0"/>
</Connectionstrings>
Note: The name of the database connection string is very important here. When EF code-first is used in the future, you can use it to find the database. Data Source = | datadirectory | mvcmusicstore is used in the Link string. here, datadirectory refers to the app_data folder in the project.
If SQL Server is used, use the following link string. Note that providername should also be replaced with the provider used by sqlserver.
<! --Database connection string Configuration-->
<Connectionstrings>
<AddName= "Musicstoreentities"
Connectionstring= "Server =. \ sqlexpress; database = musicstore; Integrated Security = true ;"
Providername= "System. Data. sqlclient"/>
</Connectionstrings>
Add context class
Right-click the model folder and add a new file named musicstoreentities. CS. Note that the name of this class must be the same as that of the database connection string.
This class will reflect the context of the Entity Framework database to process creation, read, update, and deletion operations. The Code is as follows:
UsingSystem. Data. entity;
NamespaceMvcmusicstore. Models
{
Public ClassMusicstoreentities:
Dbcontext
{
PublicDbset <album> albums {Get;Set;}
PublicDbset <genre> genres {Get;Set;}
PublicDbset <artist> artists {Get;Set;}
}
}
Note that the system. Data. entity namespace is used here. Remember to use it.
No other configurations or specific interfaces are required. by extending the dbcontext base class, we have to use the musicstoreentities class to process our database operations. Now, let's start, first, add some attributes for our class to obtain additional information from the database.
Add classified store data
For code first, we first define the model, then create a database through the model, and even do not need to write an insert statement. We can use the standard C # code to create records in the table.
We first add some data to the newly created database through Entity Framework through some seed data. First, create our store category, which needs to be completed through a genres list and an album. In the MvcMusicStore-Asset.zip file, there is a class that is saved in the code folder that contains the file for simple data creation.
In the models folder in code, locate the sampledata. CS file and add it to the models folder, as shown below.
Now, we need to add some code to tell Entity Framework about the sampledata class. Double-click the global. asax file and open it. In the application_start method, add the following lines.
//It is generally used for website initialization.
Protected VoidApplication_start ()
{
System. Data. entity. database. setinitializer (NewMvcmusicstore. Models. sampledata ());
Arearegistration. registerallareas ();
Registerglobalfilters (globalfilters. filters );
Registerroutes (routetable. routes );
}
This method is used to initialize the database and then fill in some data.
In this way, the Entity Framework configuration is completed.
Query a database
Now, let's update our storecontroller to replace the previously simulated data and call our database to query the actual data. We first define a field in storecontroller to access the object instance of our musicstoreeneities class, which is named storedb.
UsingMvcmusicstore. models;
NamespaceMvcmusicstore. Controllers
{
Public ClassStorecontroller: Controller
{
Musicstoreentities storedb =NewMusicstoreentities ();
Update index action to query the database
The musicstoreentities class provides a set of data tables in the database through the Entity Framework. It updates the index action method of the storecontroller to obtain all the classified data. We used hard-coded data. Now we can use the generes set of Entity Framework to replace it.
For EF usage, I suggest you understand the repository mode.
//
//Get:/store/
PublicActionresult index ()
{
VaRGenres = storedb. genres. tolist ();
Return This. View (genres );
}
We still return the same storeindexviewmodel if you do not need to modify the view template.
When you run the program and access the/store address, we can now see the list of categories in the database.
Use data in the database to update browsing and details pages
When the/store/browse? Genre =[Some-Genre]When accessing the Browse action, we need to obtain the corresponding album by the genre name. For our music store, the name of each genre is unique, you can use the single extension method in LINQ to obtain the Unique Genre object in the query results.
VaRExample = storedb. genres. Single (G => G. Name = "Disco ");
The single method uses a Lambda expression as the parameter, indicating that we want to obtain a single genre object that matches the specified value. In the preceding example, we will obtain the genre object named Disco.
Through EF, we can also obtain the objects related to the genre while obtaining the objects of the genre. For example, if an album belongs to this genre, we can obtain the relevant album information in advance, in this case, we need to modify the above query, including the album information. You can use the include method to specify the information you want to obtain. This method is very effective. In this way, you can obtain the genre object in a data access, you can also obtain related album objects.
After the update, our action method will look like the following.
///Store/browse? Genre = disco
PublicActionresult browse (StringGenre)
{
VaRGenremodel = storedb. genres. Include ("Albums"). Single (G => G. Name = genre );
Return This. View (genremodel );
}
Note that there is a set attribute named albums in the genre attribute of the genre.
Then, we can update the store's browse view to display the corresponding album, open the view template, and add a list.
@ Model mvcmusicstore. Models. Genre
@{
Viewbag. Title ="Browse";
}
<H2>
Browsing genre: @ model. Name </H2>
<Ul>
@ Foreach (VaRAlbumInModel. albums)
{
<Li>
@ Album. Title
</LI>
}
</Ul>
Run the program, browse/store/browse? Genre = jazz. Now you can see the album data stored in the database.
Similarly, we can modify the details to obtain the album object through the passed parameters. The modified method is as follows.
///Store/details/5
PublicActionresult details (IntID)
{
VaRAlbum = storedb. albums. Find (ID );
ReturnView (album );
}
Run the program and access/store/details/1. You can see the following content.
Update the Browse view and provide a hyperlink to the details page. Here, we use the actionlink method. The modified view is as follows.
When browsing browse again, each album should have become a link ,: