MVC+EF+SQL Server项目创建数据库连接流程

这里选择空的模板,有需要的可以选择MVC模板。

创建好项目后添加EF的NuGet包

新建 MyDBContext 类用来连接数据库(记得添加引用 using System.Data.Entity;)
public class MyDBContext:DbContext
{
// 注:这是连接sqlserver字符串,具体到时候可以放在配置文件中
public MyDBContext() : base("Data Source=.;Initial Catalog=InformationProDB;Integrated Security=True") { }
}
此时项目与数据库之前的桥梁已经搭建完了,下面来试验一下是否成功。
新建 Students 类
public class Students
{
public int ID { get; set; }
public string StuCode { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Sex { get; set; }
}
添加实体模型 public DbSet<Students> Students { get; set; }

新建HomeController并添加index视图,添加一条入库测试

public string Index()
{
MyDBContext conn = new MyDBContext();
Students s = new Students();
s.Name = "赵五";
s.StuCode = "stu_10006";
s.Age = 12;
s.Sex = 1;
conn.Students.Add(s);
if (conn.SaveChanges() > 0)
{
return ("添加成功");
}
else
{
return ("添加失败");
}
}
测试结果:



浙公网安备 33010602011771号