Code first codes are preferred.
On the code:
Create the data model you need (or you can think of the data sheet you need):
namespacecodefirstdemo.models{ Public classStudent { Public intId {Get;Set; } Public stringName {Get;Set; } } Public classTeacher { Public intId {Get;Set; } Public stringName {Get;Set; } }}
Creates a new Codefirstdb class that inherits from the DbContext class. (Note introducing a reference to the System.Data.Entity namespace):
namespace codefirstdemo.models{ publicclass codefirstdb:dbcontext { Public Get Set ; } Public Get Set ; } }}
Database creation:
1. Seeding the database.
2. To ensure that the database is synchronized with the model (temporarily regardless of the data migration issue), recreate the database at each startup of the program startup (created only when a model change is detected)
protected void Application_Start () { // re-creating the database when the program detects a model change each time it starts Database.setinitializer (new Codefirstdemo ()); Arearegistration.registerallareas (); Webapiconfig.register (globalconfiguration.configuration); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (bundletable.bundles); Authconfig.registerauth (); }
/// <summary> ///Seeding Database/// </summary> Public classCodefirstdemo:dropcreatedatabasealways<codefirstdb> { protected Override voidSeed (Codefirstdb context) {context. Student.add (NewStudent {Id =1, Name ="Xiao Ming" }); Context. Teacher.add (NewTeacher {Id =1, Name ="Lao Wang" }); Base. Seed (context); } }
Program calls:
Public actionresult Index () { new codefirstdb (); " Modify This template to jump-start your ASP application. " ; var data = db. Student.tolist (); return View (); }
After the call is complete, view the results in your App_Data folder.
Note: If you want to assign a value to a field default value. In the default constructor.
Code First of MVC learning