MVC5_学习笔记_1_CodeFirst

MVC5_EF6_1

Code First--准备工作

Code First 是先建Model再生成数据库以及表

  1. 首先创建一个类取名为UserInfo,一个类对应一个数据库的一张表

    public class UserInfo
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    }
  2. 新建一个文件夹取名为DAL,创建一个数据上下文CodeFirstDBContext

    public class CodeFirstDBContext : DbContext
    {
    public RuanGongContext()
    : base("CodeFirstDB")
    {
    }
    public DbSet<UserInfo> UserInfos { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;();//是以s结尾,如UserInfos,这段代码是去掉s 以UserInfo这种形式命名表名
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;();//是以s结尾,如UserInfos,这段代码是去掉s 以UserInfo这种形式命名表名
    }
    }

    此处继承了DbContextt, "public RuanGongContext(): base("CodeFirstDB")" 这段代码使得该数据上下文与连接串为CodeFirstDB的数据连接串相联系,即RuanGongContext对应连接串为CodeFirstDB的数据库

  3. 接下来需要设置Web.config中的数据连接串了

    <connectionStrings>
    <add name="CodeFirstDB" connectionString="Persist Security Info=False;User ID=sa;Password=123;Initial Catalog=RuanGongDB;Data Source=127.0.0.1\SQLEXPRESS"
    providerName="System.Data.SqlClient" />
    </connectionStrings>

    此时编译一下在数据库中就会创建对应的UserInfo表,为了方便可向数据库中加入初始数据

  4. 通过种子Seed初始化数据,在DAL中新建一个CodeFirstDBInitializer类,加入代码

    public class CodeFirstDBInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<CodeFirstDBContext>
    {
    protected override void Seed(CodeFirstDBContext context)
    {
    var UserInfos = new List<UserInfo>
    {
    new UserInfo{Name="Alexander",Age=21)},
    new UserInfo{Name="Kate",Age=23)},
    new UserInfo{Name="Bob",Age=20)},
    new UserInfo{Name="Tom",Age=24)},
    };
    UserInfos.ForEach(s =&gt; context.UserInfo.Add(s));
    context.SaveChanges();
    }
    UserInfos.ForEach(s =&gt; context.UserInfo.Add(s));
    context.SaveChanges();
    }
    }

    在网站运行之前需要初始化数据,则需要在Web.config中加入以下代码

    <entityFramework>
    <contexts>
    <context type="ContosoUniversity.DAL.CodeFirstDBContext, CodeFirstDB">
    <databaseInitializer type="ContosoUniversity.DAL.CodeFirstDBContextInitializer, CodeFirstDB" />
    </context>
    </contexts>
    </entityFramework>

    这里有两行代码,context中的type是对应的类名和程序集名,第二行是初始化数据的类名和程序名 作为一种在web.config中设置初始值设定项的替代方法,可以通过在Global.asax.cs中Application_Start方法中增加Database.SetInitializer语句来实现同样的功能。

    此时,准备工作已经结束,运行网站相应的数据会被初始化到数据库中

posted @   杰哥很忙  阅读(287)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示