In this article we will see how a Code First Approach provides an alternative to the Database First and model First approaches to lớn the Entity Data Model.
Bạn đang xem: Code first example
Entity Framework is the Microsoft preferred method of data access for .NET applications. It supports strongly-typed access through LINQ. Entity Framework also allows developers to lớn program against a conceptual model that reflects application xúc tích rather than a relational model that reflects the database structure. Entity Framework can be used from an ASP.NET Application, (using Entity Data Source) or in ASP.NET MVC, etc. In this article, we will be creating this using MVC App và we"ll be using Visual Studio 2012 for the demo.
The Code First Approach provides an alternative to lớn the Database First and model First approaches khổng lồ the Entity Data mã sản phẩm and creates a database for us based on our classes that we will be creating in this article.
Create a new ASP.NET MVC Project by New > Project > ASP.NET MVC 4 web Application > Empty Template; you will get following structure:
Right-click on the References thư mục and select "Manage NuGet Packages". Alternatively you can install it from Tools > Library Package Manager > Package Manager Console & type "Install-Package EntityFramework". Okay, let"s vày this from a NuGet Package window; type "Entity Framework" into the search box và click to install it. After installation you will see a new library file in the References folder "EntityFramework".
Right-click on the Models thư mục to add a new class file named "Student.cs" và type the following code:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; namespaceCode_First_Approach_in_Entity_Framework.Models publicclassStudent publicintStudentIDget;set; publicstringNameget;set; publicstringAddressget;set; publicstringMobileget;set;
So, I have declared four properties: StudentID, Name, Address and Mobile. Now go ahead and create a class khổng lồ manage the link with the database the above properties by inheriting DbContext. Lưu ý to usethe namespace System.Data.Entity.
Right-click on the Models folder to showroom a new class file named "StudentContext.cs" & enter the following code:
usingSystem; usingSystem.Collections.Generic; usingSystem.Data.Entity; usingSystem.Linq; usingSystem.Web; namespaceCode_First_Approach_in_Entity_Framework.Models publicclassStudentContext:DbContext publicDbSetStudentsget;set;
Now, this DbContext will vì chưng many things for us such as it will create databases và tables. You can kiểm tra your newly added database file.
Build the solution here by menu Build > Build Solution because I want mã sản phẩm class và Data context class to lớn beavailable for me in the địa chỉ cửa hàng Controller window. Go ahead and địa chỉ cửa hàng a controller; to vì that right-click on the Controllers thư mục in the Solution Explorer và select add > Controller & use the name "StudentController" & make the following selections asshown in the image below:
Let"s run the project. You will get an error page as given below; this is because the application is expecting "Home" controller by default và we don"t have this controller instead we have a "student" controller. You will see how to fix this in the next step.
For now request the "student" controller using an URL something like http://localhost:portnumber/student and try khổng lồ perform CRUD operation.
When you run the application, the very first thing you will get is an error page, because the application is expecting "Home" as a controller by default but we don"t have a"Home" controller in our application instead we have "Student" so we need to lớn modify the mặc định hit by the application. For this, find a tệp tin "RouteConfig.cs" in the "App_Start" thư mục and make a single change.
routes.MapRoute( name:"Default", url:"controller/action/id", defaults:newcontroller="student",action="Index",id=UrlParameter.Optional );
The only change is just to lớn replace the controller value to "student". Now run the application again, you will not see that error page anymore.
If you are interested in learning more about Routing, then go ahead & learn it from ScottGu"s blog post here:
Assume, if you want lớn validate your data before sending it to lớn the database or you want khổng lồ define any validation expression or want to lớn make any field as "Required". For this we can take advantage of the "System.ComponentModel.DataAnnotations.dll" assembly shipped with the MVC package & you can find it in the References folder. Now to enable the validation, xuất hiện the "Student.cs" model and add some validation lines, as in:
Because, this class file directly represents the database table"s structure and making any changes here is subject of "Code First Migrations" to lớn update database and its tables và that why you got above error. Remember, you will thua kém all your records if you migrate your database here. Still Microsoft is working on this subject to lớn avoid data loss, hoping lớn see such functionality in coming releases. Let"s move lớn next step to vày database migration.
If you want to lớn learn more about "Data Validation Using Data Annotations" then please read: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs.
Now, don"t worry about data loss here và go ahead lớn update the database table to chạy thử the preceding validation rules.
So, now if you want khổng lồ see where the database has been created for this app. Mở cửa the directory where you have created your phầm mềm and open the App_Data folder; you will find you database files.
Now the question is how to lớn change the database instance name, this is so long here. Let"s learn it inanother step.
In the above image you will see our default database name is ""Code_First_Approach_in_Entity_Framework.Models.StudentContext". Let"s change it. Remember you will again thua your records.
Find a very nice clip on this title by Julie Lerman here http://msdn.microsoft.com/en-us/data/gg715119.
I have done a couple of clip posts on MVC basics, if you are interested go và watch at my YouTube channel here http://www.youtube.com/user/abhimanyukumarvatsa.