I basically designed the db first, so I wrote the program according to the existing table.
1.web.config Configure DB connection string, Connection string name is DefaultConnection
<connectionStrings> <!--<add name="defaultconnection"connectionstring="Data source= (LocalDb) \v11.0; attachdbfilename=| Datadirectory|\aspnet-tlt-20150912072507.mdf;initial catalog=aspnet-tlt-20150912072507;integrated Security=True "ProviderName="System.Data.SqlClient"/>--> <add name="defaultconnection"connectionstring="server=120.25.**.**;D atabase=log4net;uid=log4net;pwd=*******;"Providername="System.Data.SqlClient"/> </connectionStrings>
2. Create a new model named Log in models, if you do not specify the Table,entity framework will default to the DB name models table, that is, a suffix more than one s. But I am an already existing table, so I will assign a tablename to the entity, which can be done by [Table ("Log")], as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations.Schema;usingSystem.Linq;usingsystem.web;namespaceTLT. models{//[Table ("Log")] Public classLog { PublicInt32 ID {Get;Set; } PublicDateTime Date {Get;Set; } Public stringThread {Get;Set; } Public stringLevel {Get;Set; } Public stringLogger {Get;Set; } Public stringMessage {Get;Set; } }}
3.model finished, then the most important thing is to have a dbcontext, create a new directory Dal, add a class inheriting DbContext ApplicationDbContext.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingTLT. Models;usingSystem.Data.Entity;namespaceTLT. dal{ Public classApplicationdbcontext:dbcontext { PublicApplicationdbcontext ():Base("defaultconnection") { } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base. Onmodelcreating (ModelBuilder); Modelbuilder.entity<Log> (). ToTable ("Log"); } PublicDbset<log> Log {Get;Set; } }}
The defaultconnection in base of the first constructor is just the DB connection string name we configured in Web. config, and in onmodelcreating we can specify the tables in the database for each model.
This is basically done, and you can test whether you can read the data in the following way.
// Get:log Public actionresult Index () { usingnew applicationdbcontext ()) { var log = db. Log.tolist (); return View (log); } }
Entity Framework 6 Code first created