您的位置:首页 > 其它

.net core mvc中使用ef

2017-06-17 18:26 316 查看
             使用环境win7+2017

  一.新建一个.net core的MVC项目

           

               



              新建好项目后,不能像以前一样直接在新建项中添加ef,

              需要用命令在添加ef的依赖

  

  二.使用Nuget添加EF的依赖


          

               输入命令:  Install-Package
Microsoft.EntityFrameworkCore.SqlServer

               


              安装成功后就可以在Nuget依赖项中看到

               


  三.如果是使用db first,需要根据数据库生成model,就还需要使用命令添加两个依赖

             

 
      Install-Package Microsoft.EntityFrameworkCore.Tools

 
     
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

            

             安装成功后就可以在Nuget依赖项中看到

              


 四.更具一个命令就可以从数据库生成model了       

              Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

                  

                     注:执行这一步的时候出现了点问题 ,因为系统是win7,powershell版本太低了,不支持这个命令,需要安装

                        3.0以上的powershell版本才行         





           
添加成功后在models可以看到, 生成了上下文对象与和表对应的model

               



             

                

         现在就可以使用EF了

           

public IActionResult Index()
{

FoodContext fc = new FoodContext();

List<ProType> ptlist = fc.ProType.ToList();

ViewBag.ptlist = ptlist;

return View();
}


         



 五.使用依赖注入来装载EF的上下文对象

           

                .net core中用了不少的依赖注入,官方文档中也推荐使用           



                 1:删除方法

                 

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"Server=.;Database=Food;Trusted_Connection=True;");
}


                 2:添加方法

                

public FoodContext(DbContextOptions<FoodContext> options)
: base(options)
{

}
                        

                       添加的是一个构造函数用于注入         

                     

                3:在startup.cs的ConfigureServices方法中添加依赖注入 
                 




public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();

services.AddDbContext<FoodContext>(option => {
option.UseSqlServer("Data Source =.; Initial Catalog = EFCore_dbfirst; User ID = sa; Password = sa.123");
});

}


                  注:usersqlserver是一个扩展方法,需要添加ef core的引用using Microsoft.EntityFrameworkCore;





        微软官方文档:

          https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: