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();
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代码实践的更多相关文章
- ReactiveCocoa代码实践之-更多思考
三.ReactiveCocoa代码实践之-更多思考 1. RACObserve()宏形参写法的区别 之前写代码考虑过 RACObserve(self.timeLabel , text) 和 RACOb ...
- ReactiveCocoa代码实践之-RAC网络请求重构
前言 RAC相比以往的开发模式主要有以下优点:提供了统一的消息传递机制:提供了多种奇妙且高效的信号操作方法:配合MVVM设计模式和RAC宏绑定减少多端依赖. RAC的理论知识非常深厚,包含有FRP,高 ...
- 深刻理解Python中的元类(metaclass)--代码实践
根据http://blog.jobbole.com/21351/所作的代码实践. 这篇讲得不错,但以我现在的水平,用到的机会是很少的啦... #coding=utf-8 class ObjectCre ...
- Java的BIO和NIO很难懂?用代码实践给你看,再不懂我转行!
本文原题“从实践角度重新理解BIO和NIO”,原文由Object分享,为了更好的内容表现力,收录时有改动. 1.引言 这段时间自己在看一些Java中BIO和NIO之类的东西,也看了很多博客,发现各种关 ...
- TextCNN代码实践
在上文<TextCNN论文解读>中已经介绍了TextCNN的原理,本文通过tf2.0来做代码实践. 数据集:来自中文任务基准测评的数据集IFLYTEK 导库 import os impor ...
- word2vector代码实践
引子 在上次的 <word2vector论文笔记>中大致介绍了两种词向量训练方法的原理及优劣,这篇咱们以skip-gram算法为例来代码实践一把. 当前教程参考:A Word2Vec Ke ...
- 机器学习(四):通俗理解支持向量机SVM及代码实践
上一篇文章我们介绍了使用逻辑回归来处理分类问题,本文我们讲一个更强大的分类模型.本文依旧侧重代码实践,你会发现我们解决问题的手段越来越丰富,问题处理起来越来越简单. 支持向量机(Support Vec ...
- .net core web api + Autofac + EFCore 个人实践
1.背景 去年时候,写过一篇<Vue2.0 + Element-UI + WebAPI实践:简易个人记账系统>,采用Asp.net Web API + Element-UI.当时主要是为了 ...
- ReactiveCocoa代码实践之-UI组件的RAC信号操作
上一节是自己对网络层的一些重构,本节是自己一些代码小实践做出的一些demo程序,基本涵盖大多数UI控件操作. 一.用UISlider实现调色板 假设我们现在做一个demo,上面有一个View用来展示颜 ...
随机推荐
- 【UOJ#390】【UNR#3】百鸽笼(动态规划,容斥)
[UOJ#390][UNR#3]百鸽笼(动态规划,容斥) 题面 UOJ 题解 发现这就是题解里说的:"火山喷发概率问题"(大雾 考虑如果是暴力的话,你需要记录下当前每一个位置的鸽笼 ...
- 【题解】Informacije [COCI2012]
[题解]Informacije [COCI2012] 传送门:官方题面 [题目描述] 有一个长度为 \(n\) 的 序列 \(a\)(由 \([1,n]\) 中的数组成,且每个数只会出现一次),现给出 ...
- 使用IDEA的Git插件上传项目教程
如何使用IDEA的Git插件上传项目 一.在https://www.cnblogs.com/zyx110/p/10799387.html中下载 二.注册码云账号 搜索gitee码云插件并安装
- Error: Opening Robot Framework log failed on mac jenkins
For resolve your problem you must : Connect on your jenkins url (http://[IP]:8080/) Click on Manage ...
- 开发技术--浅谈Python函数
开发|浅谈Python函数 函数在实际使用中有很多不一样的小九九,我将从最基础的函数内容,延伸出函数的高级用法.此文非科普片~~ 前言 目前所有的文章思想格式都是:知识+情感. 知识:对于所有的知识点 ...
- ASP.NET Core系列:依赖注入
1. 控制反转(IoC) 控制反转(Inversion of Control,IoC),是面向对象编程中的一种设计原则,用来降低代码之间的耦合度. 1.1 依赖倒置 依赖原则: (1)高层次的模块不应 ...
- 解决 bash: vue command not found
背景 : win10 使用 yarn 全局 安装 vue/cli 后 yarn global add @vue/cli 提示安装成功 使用vue create 提示 bash: ...
- APS系统生产流转方式和批量算法研究
01.前言 在经济领域,生产型企业是经济的根基,有了生产型企业生产出的各种产品,才有物流.网上购物和金融融资等活动.对于生产型企业,其制造能力是其核心竞争力.如何提升制造能力一直是生产型企业面临的课题 ...
- rhel安装输入法
# yum install "@Chinese Support" 安装完成后,设置输入法: System -> Preferences -> Input Method
- UVa 202 Repeating Decimals 题解
The decimal expansion of the fraction 1/33 is 0.03, where the 03 is used to indicate that the cycle ...