在 Startup 的 ConfigureServices 里面注册相关服务
public void ConfigureServices(IServiceCollection services) { var connectionString = @"Server=.;Database=BloggingWithRepository;Trusted_Connection=True;"; services.AddDbContext<BloggingContext>(option => option.UseSqlServer(connectionString)); services.AddScoped<BloggingUnitOfWork>(); services.AddTransient(typeof(IBlogggingRepositoryBase<,>), typeof(BlogggingRepositoryBase<,>)); }这里 BloggingContext 和 UnitOfWork 的生命周期为 Scoped。
在 Controller 里面调用并测试
public class BlogsController : ControllerBase { private readonly IBlogggingRepositoryBase<Blog, int> _blogRepository; private readonly IBlogggingRepositoryBase<Post, int> _postRepository; private readonly BloggingUnitOfWork _unitOfWork; public BlogsController(IBlogggingRepositoryBase<Blog, int> blogRepository, IBlogggingRepositoryBase<Post, int> postRepository, BloggingUnitOfWork unitOfWork) { _blogRepository = blogRepository; _postRepository = postRepository; _unitOfWork = unitOfWork; } [HttpGet] public async Task<IActionResult> GetBlogs() { var blogs = await _blogRepository.GetAsync(); return Ok(blogs); } [HttpPost] public async Task<IActionResult> PostBlog([FromBody] Blog blog) { if (!ModelState.IsValid) { return BadRequest(ModelState); } //await _blogRepository.AddAsync(new Blog { Url = "http://sample.com/4", Rating = 0 }); //await _postRepository.AddAsync(new Post { Title = "Title4", Content = "BlogId_1 Post_3", BlogId = 1 }); var result = await _blogRepository.AddAsync(blog); await _unitOfWork.SaveChangesAsync(); return CreatedAtAction("GetBlog", new { id = blog.Id }, blog); } } 使用 EF Core(DB First)EF Core 的 DB First 是通过 Scaffold-DbContext 命令根据已经存在的数据库创建实体类和context类。
可以通过PM> get-help scaffold-dbcontext –detailed查看命令的详细参数
Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-ContextDir <String>] [-Context <String>] [-Schemas <String[]>] [-Tables <String[]>] [-DataAnnotations] [-UseDatabaseNames] [-Force] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]使用之前创建的 blogging 数据库简单的测试一下:
新建一个项目,然后通过 Nuget 安装 EF Core 引用
Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools
执行命令创建实体
Scaffold-DbContext "Server=CD02SZV3600503\SQLEXPRESS;Database=BloggingWithRepository;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models执行成功后可以看到在 Models 文件夹下面创建的实体类和 Context 类。
源代码Github
参考
Entity Framework Core
Code First 开发系列
Entity Framework Core Tutorial
ASP.NET Core MVC with EF Core - Advanced
UnitOfWork
commonfeatures-webapi-aspnetcore