Aspnetcore2.0中Entityframeworkcore及Autofac的使用(二)(附Demo)(
一,通過Entityframeworkcore中DbFirst模式創建模型
這裏只說一下Entityframeworkcore中DbFirst模式創建模型,想了解CodeFirst的可以自行度娘,還是在原有項目中創建一個Model類庫,然後通過通過vs中NuGet的程序包管理控制臺執行
安裝EntityFrameworkCore類工具包,:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools
註意安裝以下類庫版本需與AspNetCore.Model自建類庫的Core版本相適應。
通過執行以下命令生成實體類與上下文
Scaffold-dbcontext "Server=.;database=test1;Integrated Security=false;user id=****;password=*****" Microsoft.EntityFrameworkCore.SqlServer -outputdir Models
生成成功後要修改一下test1Context.cs中的代碼
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) //{// if (!optionsBuilder.IsConfigured) // { // optionsBuilder.UseSqlServer(@"Server=zhang;database=test1;Integrated Security=false;user id=sa;password=123456"); // } //} //自定義定義構造器 public test1Context(DbContextOptions options):base(options) { }
註意:每次更新數據庫都要修改test1Context.cs中的代碼
新建BookService.cs
namespace AspNetCore.Service { public class BookService { private test1Context _context = null; public BookService(test1Context context) { this._context = context; } public Book Get(long id) { return _context.Book.Find(id); } } }View Code
下一步我們就要通過Controller把數據呈現出來,在這裏我們要把數據庫連接放到appsettings.json配置文件裏
{ "ConnectionStrings": { "connstr": "Data Source=.;Initial Catalog=test1;User ID=*****; Password=**********" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }View Code
修改一下項目啟動文件Startup.cs:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //配置上下文 services.AddDbContext<test1Context>(options => options.UseSqlServer(Configuration.GetConnectionString("connstr"))); //默認類庫聲明周期 services.AddScoped(typeof(BookService)); }View Code
新建BookController中的代碼:
public class BookController : Controller { //依賴註入 private readonly BookService _service = null; public BookController(BookService service) { this._service = service; } public IActionResult Index() { return Content($"第一本書的書名是[{_service.Get(1).Name}]") ; } }View Code
結果:
^v^是不是很開森
Aspnetcore2.0中Entityframeworkcore及Autofac的使用(二)(附Demo)(