1、首先用VS2017新建一个Asp.Net Core Web 应用程序项目,然后在我们的项目中安装EF Core程序包,可以通过如下2种方式获取。
1)在Visual Studio中,使用程序包管理控制台输入命令行:
Install-Package Microsoft.EntityFrameworkCore.SqlServer -version 2.0.0
2)在nuget中找 Microsoft.EntityFrameworkCode.SqlServer
安装完成后,定义一个模型(模型是由实体类和数据库会话派生的上下文),例如
public class BaseDbContext : DbContext
{
public BaseDbContext(DbContextOptions<BaseDbContext> options) : base(options)
{
}
public DbSet<UserInfo> Users { get; set; }
}
对比之前的数据库会话派生的上下文,我们将重写方法OnConfiguring去掉了,在构造函数中声明DbContextoptions变量。接着我们创建一个数据库仓储类
public interface IUserInfoDao : IDao<UserInfo>
{
IList<UserInfo> GetAll();
}
public class UserInfoDao: IUserInfoDao
{
private BaseDbContext _dbContext;
public UserInfoDao(BaseDbContext dbContext)
{
this._dbContext = dbContext;
}
public override IList<UserInfo> FindAll()
{
return this._dbContext.Users.ToList();
}
}
然后通过在Asp.Net Core下的StartUp类中使用依赖注入注册数据库会话上下文
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<BaseDbContext>(options => options.UseSqlServer(connectionString));
services.AddTransient<IUserInfoDao, UserInfoDao>();
services.AddMvc();
}
一般数据连接字符串会动态配置,我在appsettings.json文件中配置了ConnectionStrings节点,然后通过Configuration.GetConnectionString获取到它。
最后在控制器中访问仓储类
public class UserInfoController : Controller
{
private IUserInfoDao _userDao;
public UserInfoController(IUserInfoDao userDao)
{
this._userDao = userDao;
}
// GET: /<controller>/
public IActionResult Index()
{
IList<UserInfo> users = this._userDao.GetAll();
return View();
}
}
2101

被折叠的 条评论
为什么被折叠?



