Entity Framework 6 Code First创建

基本上我是DB先设计好的,所以就按现存在的table去写程式。

1.Web.config里配置Db连接字串,Connection String Name为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.**.**;Database=Log4Net;uid=Log4Net;pwd=*******;" providerName="System.Data.SqlClient" />    
  </connectionStrings>

2.在Models里新建一个名为Log的model,如果没有指定table,entity framework会默认在DB里建名字为models的table,也就是后缀多一个s。不过我是已经存在的表,所以会给实体指定一个tablename,可以通过[Table("Log")]这种方式,如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace TLT.Models
{
    //[Table("Log")]
    public class Log
    {
        public Int32 ID { get; set; }

        public DateTime Date { get; set; }

        public string Thread { get; set; }

        public string Level { get; set; }

        public string Logger { get; set; }

        public string Message { get; set; }
    }
}

3.model建完了,接下去最重要的就是要有一个DbContext,新建一个目录DAL,增加一个继承DbContext的类ApplicationDbContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using TLT.Models;
using System.Data.Entity;

namespace TLT.DAL
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Log>().ToTable("Log");
        }

        public DbSet<Log> Log { get; set; }
    }
}

第一个构造函数的base里的DefaultConnection就是刚刚我们在Web.config配置的DB连接字串名称,在OnModelCreating里,我们可以给每一个model指定数据库中的表。

至此已经基本完成,可以用下面的方式测试是否可以读取数据。

 // GET: Log
        public ActionResult Index()
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var log = db.Log.ToList();
                return View(log);
            }            
        }

 

posted @ 2015-09-12 21:59  lzone6  阅读(301)  评论(0编辑  收藏  举报