最近在使用EF5和Moq4.0做项目时,遇到一些问题,在此记录下:
一、 DbContext 内容
public partial class EFPub01Entities : DbContext
{
public EFPub01Entities()
: base("name=EFPub01Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Teacher> Teacher { get; set; }
}
二、使用moq模拟DbSet<Teacher>
static void Main(string[] args)
{
// 实例化上下文
EFPub01Entities dbContext = new EFPub01Entities();
// 模拟DbSet<Teacher>,并赋值给上下文的Teahcer
dbContext.Teacher = new Mock<DbSet<Teacher>>().Object;
// 查询Id为1的Teacher数据
Teacher teacher = dbContext.Teacher.Where(t => t.Id == 1).FirstOrDefault();
Console.WriteLine("教师Id:{0}, 教师姓名{1}"