本人搭建Test环境的目的是测试N+1查询和LazyLoading,参考书籍:你必须掌握的Entity Framework 6.x与Core 2.0, 工具:VS2019
- 创建Console application
- Add entityframework
- Add class and context class
class Program
{
static void Main(string[] args)
{
using (var test = new TestContext())
{
Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>());
test.Owners.Add(new Owner()
{
Name = "owner1",
Cats = new List<Cat>
{
new Cat()
{
Name = "Cat1",
Age = 1,
BirthTime = DateTime.Now,
Color = "Red"
},
new Cat()
{
Name = "Cat2",
Age = 2,
BirthTime = DateTime.Now,
Color = "Yellow"
}
}
});
test.Owners.Add(new Owner()
{
Name = "owner11",
Cats = new List<Cat>
{
new Cat()
{
Name = "Cat11",
Age = 1,
BirthTime = DateTime.Now,
Color = "Green"
}
}
});
test.Owners.Add(new Owner()
{
Name = "owner2",
Cats = new List<Cat>
{
new Cat()
{
Name = "Cat3",
Age = 1,
BirthTime = DateTime.Now,
Color = "Green"
},
new Cat()
{
Name = "Cat4",
Age = 2,
BirthTime = DateTime.Now,
Color = "Blue"
}
}
});
test.SaveChanges();
}
}
}
public class Cat
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime BirthTime { get; set; }
public string Color { get; set; }
public int OwnerId { get; set; }
}
public class Owner
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Cat> Cats { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Cat> Cats { get; set; }
public DbSet<Owner> Owners { get; set; }
}
- 通过代码添加测试数据,删除代码后,进行其他测试
- Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>()); 每次运行代码都会重新生成数据库
- 不设置connectionstring的情况下,数据库生成在VS安装自带的SqlServer实例,版本为Microsoft SQL Server Express Edition。
-
可通过VS的SQL Server Object Explorer查看数据库
image.png
生成数据库名字:console application name + context name