当前位置:Gxlcms > 数据库问题 > ASP.NET MVC EF 数据库初试水

ASP.NET MVC EF 数据库初试水

时间:2021-07-01 10:21:17 帮助过:20人阅读

首先,创建MVC项目,引用EntityFramework,创建了一个Student类

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

namespace EFF.Models
{
    public class Student
    {
        public int StudentID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public int Sexsk { get; set; }
    }
}

之后,新建一个DBContext.cs(这货应该是用来创建数据库的)

using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using EFF.Models;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace EFF
{
    public class DBEFFContext:DbContext
    {
        public DbSet<Student> Students { get; set; }
        
    }
}

当然,我们需要连接数据库

在Web.config上,在<configuration>中加上

  <connectionStrings>
    <add name="DBEFFContext" connectionString="Data Source=.; Initial Catalog=ISEE;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

连接数据库,库名:ISEE(我看看撒)

然后我运行看看下撒...

技术分享

东西是出来了,但是....

修改model:Student的时候,再次运行,就会报错,没办法,只好查查了

技术分享

 

结果查到了:

EF Code First Migrations数据库迁移(这货有链接吧?)

看看,虽然解决了,但是每次一运行都需要....在VS的工具->NuGet包管理器->程序包管理控制台里面运行....

安装EntityFramework:
PM> Install-Package EntityFramework

生成Configuration.cs,
PM> Enable-Migrations -EnableAutomaticMigrations(之后记得将AutomaticMigrationsEnabled改为true)

执行成功后,在Migrations文件夹中新增类文件201309201556388_InitialCreate.cs,
PM> Add-Migration InitialCreate

这货应该是更新吧
PM> Update-Database -Verbose


PM> Add-Migration AddCity
  再次执行程序包管理器控制台语句

PM> Update-Database -Verbose

 

数据是还存在的,但是总觉得要是这样子,每次一改动到model,就必须这么执行一套(总感觉有点不适用....之后再去找找看)

 

感谢几位大大提供的参考资料:

MVC 使用EF Code First数据迁移之添加字段

http://blog.csdn.net/kangk1992/article/details/10107363

EF Code First Migrations数据库迁移:

http://www.cnblogs.com/libingql/p/3330880.html

 

MVC中code first方式开发,数据库的生成与更新(Ef6):

http://blog.csdn.net/chenguang79/article/details/50847550

 

ASP.NET MVC EF 数据库初试水

标签:art   pack   rbo   public   bin   detail   url   code   mvc   

人气教程排行