一.新建一個.net core的MVC項目shell
新建好項目後,不能像之前同樣直接在新建項中添加ef,數據庫
須要用命令在添加ef的依賴app
二.EF Core實體框架核心安裝:框架
工具> NuGet軟件包管理器>軟件包管理器控制檯ide
Install-Package Microsoft.EntityFrameworkCore.SqlServer函數
Install-Package Microsoft.EntityFrameworkCore.Tools工具
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design ui
安裝成功後就能夠在Nuget依賴項中看到.net
四.更具一個命令就能夠從數據庫生成model了 code
方式一:(經過現有數據庫建立模型)
Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
該命令會在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(); }
方式二:(經過模型建立數據庫)
1.建立上下文類
public class FoodContext : DbContext { public FoodContext (DbContextOptions<FoodContext> options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List< Post > Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } }
2.在startup.cs的ConfigureServices方法中中將上下文類註冊爲全局服務:
services.AddDbContext(options => options.UseSqlServer(connection));
3.在appsetting文件中增長鏈接字符串connection
4.建立數據庫
工具 - > NuGet軟件包管理器 - >軟件包管理器控制檯
//建立模型的初始表
Add-Migration InitialCreate
//將新遷移應用於數據庫
Update-Database
五.使用依賴注入來裝載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"); }); }
微軟官方文檔:
https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db