EFCore代码实践
参考:https://www.cnblogs.com/Wddpct/p/6835574.html
控制台程序依赖注入参考:https://www.cnblogs.com/Wddpct/p/7219205.html
1、模型定义
namespace Domain { public class Blog { public Blog() { Posts = new List<Post>(); } public int BlogId { get; set; } public string Url { get; set; } public string Title { get; set; } public string Author { get; set; } public DateTime CreateTime { get; set; } public virtual List<Post> Posts { get; set; } public void AddPsot(Post post) { if (Posts == null) { Posts = new List<Post>(); } Posts.Add(post); } } }
namespace Domain { public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public virtual Blog Blog { get; set; } } }
2、数据访问
using Domain; using Microsoft.EntityFrameworkCore; using System; namespace CoreEfDAL { public class ForumContext : DbContext { public ForumContext(DbContextOptions<ForumContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Blog>().Property(b => b.Url).HasMaxLength(500); modelBuilder.Entity<Blog>().Property(b => b.Title).HasMaxLength(100); modelBuilder.Entity<Blog>().Property(b => b.Author).HasMaxLength(20); modelBuilder.Entity<Blog>() .HasMany(b => b.Posts) .WithOne(b => b.Blog); } public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } } }
3、单元测试
using CoreEfDAL; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.EntityFrameworkCore.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Domain; using System; using System.IO; namespace CoreEfDAL_Test { [TestClass] public class UnitTest1 { private ForumContext GetDB() { ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); cfgBuilder.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var configuration = cfgBuilder.Build(); var conString = configuration.GetConnectionString("myblog"); var serviceCollection = new ServiceCollection(); serviceCollection.AddDbContext<ForumContext>(c => c.UseSqlServer(conString)); var db = serviceCollection.BuildServiceProvider().GetService<ForumContext>(); return db; } [TestMethod] public void AddBolgs_Test() { var db = GetDB(); var blog = new Blog { Url = "http://blogs.msdn.com/adonet", Title = "测试标题121212111", Author = "王五", CreateTime = DateTime.Now }; var post1 = new Post(); post1.Content = "ddddddd"; post1.Title = "tttttttt"; var post2 = new Post(); post2.Content = "dddxxxxdddd"; post2.Title = "ttttddddd"; var post3 = new Post(); post3.Content = "2345sdfsd"; post3.Title = "dghdfghfgh"; blog.AddPsot(post1); blog.AddPsot(post2); blog.AddPsot(post3); db.Blogs.Add(blog); var count = db.SaveChanges(); Console.WriteLine("{0} records saved to database", count); } } }
基于内存数据库的测试
[TestMethod] public void AddDepartment_Test() { var options = new DbContextOptionsBuilder<PortalContext>() .UseInMemoryDatabase(databaseName: "portaldb") .Options; using (var context = new PortalContext(options)) { Department dp = new Department(); dp.Id = "100008"; dp.Name = "根目录"; dp.ParentId = ""; dp.IsDeleted = false; context.Departments.Add(dp); var count = context.SaveChanges(); Console.WriteLine("{0} records saved to database", count); var d = context.Departments.Find("100008"); Console.WriteLine(d.Name); } }
4、API调用
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CoreEfDAL; using Domain; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; namespace CoreEfWeb.Controllers { [Route("api/[controller]")] [ApiController] public class BlogsController : ControllerBase { private readonly ForumContext _dbContext; public BlogsController(ForumContext dbContext) { _dbContext = dbContext; } private JsonResult Json(object data) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.MaxDepth = 2; settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //忽略循环引用 return new JsonResult(data, settings); } [HttpGet] public JsonResult Get() { var blogs = _dbContext.Blogs.Include(b => b.Posts).ToList(); return Json(blogs); } [HttpGet("{id}")] public JsonResult Get(int id) { var blog = _dbContext.Blogs.Include(b => b.Posts).FirstOrDefault(b => b.BlogId == id); return Json(blog); } [HttpPost] public void Post([FromBody] Blog blog) { _dbContext.Blogs.Add(blog); _dbContext.SaveChanges(); } [HttpPut("{id}")] public void Put(int id, [FromBody] Blog blog) { var blogDomain = _dbContext.Blogs.FirstOrDefault(b => b.BlogId == id); if (blogDomain != null) { blogDomain.Title = blog.Title; blogDomain.Author = blog.Author; blogDomain.Url = blog.Url; _dbContext.SaveChanges(); } } [HttpPut("{id}/author")] public void Put(int id, [FromBody] ModifyBlogAuthorRequest request) { var blogDomain = _dbContext.Blogs.FirstOrDefault(b => b.BlogId == id); if (blogDomain != null) { blogDomain.Author = request.NewAuthor; blogDomain.CreateTime = DateTime.Now; _dbContext.SaveChanges(); } } [HttpDelete("{id}")] public void Delete(int id) { var blogDomain = _dbContext.Blogs.FirstOrDefault(b => b.BlogId == id); if (blogDomain != null) { _dbContext.Blogs.Remove(blogDomain); _dbContext.SaveChanges(); } } } public class ModifyBlogAuthorRequest { public string NewAuthor { get; set; } } }
5、其他
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using CoreEfDAL; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; namespace CoreEfWeb { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ForumContext>(c => c.UseSqlServer(Configuration.GetConnectionString("myblog"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
appsettings.json 文件
{ "ConnectionStrings": { "myblog": "server=.;uid=sa;pwd=sa123456;database=efcoretest" } }
迁移命令 Add-Migration init --迁移 Updata-Database --更新数据库