zoukankan      html  css  js  c++  java
  • 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);
                }            
            }
  • 相关阅读:
    基于redission的分布式锁
    kafka在Windows环境下启动
    Synchronized优化总结
    mysql死锁总结
    索引是建立得越多越好吗?
    show processlist 详解
    RocketMQ高可用机制同步刷盘、异步刷盘和同步复制、异步复制
    Redlock红锁总结
    C#2.0泛型
    《解剖PetShop》系列之四:PetShop之ASP.NET缓存 (转)
  • 原文地址:https://www.cnblogs.com/milo-xie/p/4803694.html
Copyright © 2011-2022 走看看