当前位置: 移动技术网 > IT编程>开发语言>.net > 使用asp.net mvc + entityframework + sqlServer 搭建一个简单的code first项目

使用asp.net mvc + entityframework + sqlServer 搭建一个简单的code first项目

2018年10月31日  | 移动技术网IT编程  | 我要评论

薇安萧,快乐大本营吴尊,潮汕商人网

步骤:

1. 创建一个asp.net mvc 项目

 

1.1 项目创建好结构如下

2 通过vs安装entityframework框架

install-package entityframework

 

 3. 创建一个继承dbcontext的 mycontext类,并引用命名空间  using system.data.entity;

 

3.2 创建一个构造函数,并且实现onmodelcreating方法

public class mycontext:dbcontext
{
  public mycontext() : base("data source=.;initial catalog=test;integrated security=true") { } // 注:这是连接sqlserver字符串,具体到时候可以放在配置文件中

  protected override void onmodelcreating(dbmodelbuilder modelbuilder)
  {
    base.onmodelcreating(modelbuilder);
  }
}

 

 

4. 创建一个person模型实体类,这个的字段要和表的字段对应,也就是说你希望将来表中有哪些类型的字符,那么就在这个类中定义好这些类型字段

(这里为了简便我就定义两个字符)

public class person
{
  public int id { get; set; }  // 使用codefirst这个字符会帮我实现默认自动增长
  public string name { get; set; }
}

 

 

 5. 在mycontext中将这个实体模型类添加进去,以便将来与数据库中的表对应解析

 public dbset<person> persons { get; set; }

 

 

6. 创建一个继承entitytypeconfiguration的personconfig类,用于配置,具体实现如下:

引用命名空间 using system.data.entity.modelconfiguration;

public class personconfig:entitytypeconfiguration<person>
{
  public personconfig()
  {
    this.totable("persons"); // 这是代表将来数据库中表的名字
  }

}

 

 

 

 7. 在mycontext中的onmodelcreating添加下面代码 ,并引用命名空间 using system.reflection;

modelbuilder.configurations.addfromassembly(assembly.getexecutingassembly());

 

 

 

 

8 创建一个home控制器,添加一个数据测试下

 

 

public class homecontroller : controller
{
// get: home
public actionresult index()
{
using (mycontext ctx = new mycontext())
{
person p = new person();
p.name = "yjc";
ctx.persons.add(p);

ctx.savechanges();
}
return content("添加成功");
}
}

 

 

 

 

9 打开sql server查看

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网