参考: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();
modelBuilder.Entity<Blog>().Property(b => b.Title).HasMaxLength();
modelBuilder.Entity<Blog>().Property(b => b.Author).HasMaxLength(); 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 = "";
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("");
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 = ;
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 --更新数据库

EFCore代码实践的更多相关文章

  1. ReactiveCocoa代码实践之-更多思考

    三.ReactiveCocoa代码实践之-更多思考 1. RACObserve()宏形参写法的区别 之前写代码考虑过 RACObserve(self.timeLabel , text) 和 RACOb ...

  2. ReactiveCocoa代码实践之-RAC网络请求重构

    前言 RAC相比以往的开发模式主要有以下优点:提供了统一的消息传递机制:提供了多种奇妙且高效的信号操作方法:配合MVVM设计模式和RAC宏绑定减少多端依赖. RAC的理论知识非常深厚,包含有FRP,高 ...

  3. 深刻理解Python中的元类(metaclass)--代码实践

    根据http://blog.jobbole.com/21351/所作的代码实践. 这篇讲得不错,但以我现在的水平,用到的机会是很少的啦... #coding=utf-8 class ObjectCre ...

  4. Java的BIO和NIO很难懂?用代码实践给你看,再不懂我转行!

    本文原题“从实践角度重新理解BIO和NIO”,原文由Object分享,为了更好的内容表现力,收录时有改动. 1.引言 这段时间自己在看一些Java中BIO和NIO之类的东西,也看了很多博客,发现各种关 ...

  5. TextCNN代码实践

    在上文<TextCNN论文解读>中已经介绍了TextCNN的原理,本文通过tf2.0来做代码实践. 数据集:来自中文任务基准测评的数据集IFLYTEK 导库 import os impor ...

  6. word2vector代码实践

    引子 在上次的 <word2vector论文笔记>中大致介绍了两种词向量训练方法的原理及优劣,这篇咱们以skip-gram算法为例来代码实践一把. 当前教程参考:A Word2Vec Ke ...

  7. 机器学习(四):通俗理解支持向量机SVM及代码实践

    上一篇文章我们介绍了使用逻辑回归来处理分类问题,本文我们讲一个更强大的分类模型.本文依旧侧重代码实践,你会发现我们解决问题的手段越来越丰富,问题处理起来越来越简单. 支持向量机(Support Vec ...

  8. .net core web api + Autofac + EFCore 个人实践

    1.背景 去年时候,写过一篇<Vue2.0 + Element-UI + WebAPI实践:简易个人记账系统>,采用Asp.net Web API + Element-UI.当时主要是为了 ...

  9. ReactiveCocoa代码实践之-UI组件的RAC信号操作

    上一节是自己对网络层的一些重构,本节是自己一些代码小实践做出的一些demo程序,基本涵盖大多数UI控件操作. 一.用UISlider实现调色板 假设我们现在做一个demo,上面有一个View用来展示颜 ...

随机推荐

  1. HTTP Error 502.5 - ANCM Out-Of-Process Asp.Net Core发布到IIS失败

    问题概述 asp.net core网站发布到windows server 2012r2 IIS后,出现这个报错.dotnet xx.dll命令网站能够正常运行.说明不是程序问题. 经过一番折腾终于部署 ...

  2. ocelot性能测试

    网上搜索发现多篇文章指出ocelot的性能有问题,可是在ocelot项目issue提问中,维护者指出,ocelot的性能问题不大.瓶颈在于.net的httpclient. 我参考文章 https:// ...

  3. 锁定文件失败,打不开磁盘“D:\biehl\centos\taotao\taotao-dubbo-register\CentOS-000001.vmdk”或它所依赖的某个快照磁盘。模块“Disk”启动失败。未能启动虚拟机

    1.锁定文件失败,打不开磁盘“D:\biehl\centos\taotao\taotao-dubbo-register\CentOS-000001.vmdk”或它所依赖的某个快照磁盘.模块“Disk” ...

  4. [.NET] 控制只启动单个指定外部程序

    独立观察员 2019 年 6 月 12 日 有的时候我们程序需要启动外部程序来配合实现某些功能,比如启动一个 Cef 相关程序来承载网页.那么如果那个外部程序并没有实现单例启动,我们程序去启动它的时候 ...

  5. 关于@HtmlHelper帮助器参数

    @Html.ActionLink("首页", "Index", "Index", new{},new { @class = "na ...

  6. C# 实现敏感词过滤

    实现 该 敏感词过滤 采用的是 DFA算法,参考文章:https://blog.csdn.net/chenssy/article/details/26961957 具体 实现 步骤 如下: 第一步,构 ...

  7. MySQL5.7增量备份恢复全实战

    一. 简介 1. 增量备份 增量备份是指在一次全备份或上一次增量备份后,以后每次的备份只需备份与前一次相比增加或者被修改的文件.这就意味着,第一次增量 备份的对象是进行全备后所产生的增加和修改的文件; ...

  8. centos 安装多实例数据库

    在Centos下安装多个MySql 5.7① 下载MySql 解压版安装包② 编写安装脚本③ 将脚本和安装包放置同一目录④ 编写my.cnf文件并放置在/etc/ 目录下⑤ 赋予脚本运行权限并运行⑥ ...

  9. pwrite

    写入起始地址的偏移量,写入地址=文件开始+offset 注意:执行后,文件偏移指针不变 ssize_t pread(int fd, void *buf, size_t count, off_t off ...

  10. SMTP 与 IMAP

    (SMTP)邮件传输协议 :电子邮件写好后,由网络传输时的建立在tcp协议基础之上的协议 (IMAP)邮件访问协议:邮件到达目的服务器后,用户从用户的pc ,移动端,等到 接收邮件服务器上去访问自己的 ...