很长时间没有使用EF了,怎么创建都忘记,今天拿出来回顾一下. ~~~~~~对了这是 CodeFirst
第一步创建ASP.Net应用程序
第二步
创建之后我们可以在项目中搭建三层
在这我们需要在DAL里引用
这两个是两个引用自己需要有
1. 点击引用 2. 浏览 找到所在位置 就可以添加引用了
连接数据库需要在Web.config里面配置
<connectionStrings>
<!--放在</system.codedom>下面的<connectionStrings>
里面
connectionString是数据库的连接字符串providerName是一个引用-->
<add name="student" connectionString="Data Source=OKPTP27N9J6L7GE\TYF;Initial Catalog=WEEK3;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
第三步
在DAL之中创建上下文
第四步就是Model了 我这里创建了两个实体类 一个Student 学生 一个Class1 班级 学生是在班级里 我们需要一个外键连接Class1 班级表的CID
以下代码是Molde类库里Student类的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
//需要在引用里面引用System.ComponentModel.DataAnnotations
//[Key]用到的
using System.ComponentModel.DataAnnotations;
//[ForeignKey]用到的
using System.ComponentModel.DataAnnotations.Schema;
namespace Model
{
public class Student
{
[Key]
public int Sid { get; set; }
//姓名
public string SName { get; set; }
//年龄
public int SAge { get; set; }
//外键连接Class1的Cid
[ForeignKey("Cid")]
public virtual Class1 Class1 { get; set; }
}
}
以下代码是Model里Class1的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace Model
{
public class Class1
{
[Key]
//班级id
public int Cid { get; set; }
//班级名字
public int CName { get; set; }
//这里不需要连接别的表所以不需要外键
}
}
到这里我们就可以写代码了
举一个显示方法的例子
DAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
namespace DAL
{
public class StudentDAL
{
/// <summary>
/// 显示学生信息
/// </summary>
/// <returns></returns>
public List<Student> Show()
{
using (GoodsContext context=new GoodsContext())
{
return context.Students.ToList();
}
}
}
}
BLL中代码
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
namespace BLL
{
public class StudentBLL
{
/// <summary>
/// 显示学生信息
/// </summary>
/// <returns></returns>
/// 实例化StudentDAL
StudentDAL dal = new StudentDAL();
public List<Student> Show()
{
return dal.Show();
}
}
}
控制器
控制器代码
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Eff.Controllers
{
public class StudentController : ApiController//我们创建的是一个ApiController
{
/// <summary>
/// 显示学生信息
/// </summary>
/// <returns></returns>
StudentBLL dal = new StudentBLL();
[HttpGet]
public List<Student> Show()
{
return dal.Show();
}
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。