Asp.Net Core +EF Core 入门学习
首先在我们的项目中安装EF Core程序包,在以前的文章中我们有提到过两种方式安装。安装完成后,定义一个模型(模型是由实体类和数据库会话派生的上下文),例如
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(); } }

浙公网安备 33010602011771号