三层架构下的EntityFramework codefirst

时间:2023-03-09 04:08:02
三层架构下的EntityFramework codefirst

好久没写博客了,今天研究了EF框架的CodeFirst模式,从字面意思可以看出,代码优先.所谓代码优先,与以往的添加ado.net不同,主要是编写代码生成数据库和数据表,生成数据实体映射。个人感觉这种方法相比较自动添加数据集的方式是不错的,但是有一个缺点就是,你编写的生成数据库和数据表的代码一旦写好,改起来就比较麻烦,就算改动了一个属性,就得将数据库删掉,重新运行代码(不删也行,但是需要更新数据库,比较麻烦)。好了,请看代码:

1.项目使用三层架构,在数据访问层用的是EF框架

三层架构下的EntityFramework codefirst

2.在Model层新建Score和StudentModel类,内容如下

 namespace Students.Model
{
public class Score
{
/// <summary>
/// Gets or sets 分数ID
/// </summary>
public int ScoreID { get; set; } /// <summary>
/// Gets or sets 学生信息
/// </summary>
public virtual StudentsModel Student { get; set; } public virtual int? StudentId { get; set; } /// <summary>
/// Gets or sets 学生分数
/// </summary>
public decimal StudentScore { get; set; }
}
}

Score

 namespace Students.Model
{
public class StudentsModel
{
[Key]
public int StudentID { get; set; } /// <summary>
/// Gets or sets 学生学号
/// </summary>
public string StudentNumber { get; set; } /// <summary>
/// Gets or sets 学生姓名
/// </summary>
public string StudentName { get; set; }
}
}

StudentsModel

3.在DAL层新建一个StudentContext类,主要是构造实体对象(该类继承DbContext)

 namespace Students.DAL
{
public class StudentContext:DbContext
{
//构造实例模型
public DbSet<StudentsModel> Student { get; set; } public DbSet<Score> Score { get; set; }
}
}

StudentContext

4.配置Web.config,将连接字符串写入配置文件里

     <add name="StudentContext" connectionString="Data Source=PC201307311548;Initial Catalog=Student;Integrated Security=True" providerName="System.Data.SqlClient"/>

配置Web.config

5.实现方法

      //实例化数据源连接信息
private StudentContext context; public ScoreDAL()
{
context = new StudentContext();
} ///添加学生分数
public bool Add(Score score,string stuNum)
{
//判断学生是否存在
var student = this.context.Student.Where(p => p.StudentNumber == stuNum).FirstOrDefault();
try
{
if (student == null)
{
return false;
}
else
{
score.Student = student;
context.Score.Add(score);
context.SaveChanges();
context.Dispose();
return true;
}
}
catch (Exception e)
{
throw e;
}
} //修改学生分数
public bool Update(string stuNum,decimal score)
{
//查询学生是否有分数
var stuscore = this.context.Score.Where(p => p.Student.StudentNumber == stuNum).FirstOrDefault(); if (stuscore == null)
{
return false;
}
else
{
stuscore.StudentScore = score;
this.context.SaveChanges();
} return true;
} //删除学生信息
public bool Delete(string scoreId)
{
try
{
int id=int.Parse(scoreId);
//查询学生成绩是否存在
var score = this.context.Score.Where(p => p.ScoreID == id).FirstOrDefault(); //如果存在则执行删除,不存在则返回信息
if (score == null)
{
return true;
}
else
{
//删除成绩信息,提交到数据库执行
this.context.Score.Remove(score);
this.context.SaveChanges();
}
}
catch
{
return false;
} return true;
}

ScoreDAL示例

6.实现效果

三层架构下的EntityFramework codefirst

三层架构下的EntityFramework codefirst