• Entity层
 using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text; namespace Entity.Core
{
/// <summary>
/// DB表基础属性
/// </summary>
public abstract class BaseEntity<T>
{
public BaseEntity()
{
CreteTime = DateTime.Now;
}
/// <summary>
/// 主键Id
/// </summary>
[DataMember]
[Key]
public T Id { get; set; } /// <summary>
/// DB版号,Mysql详情参考;http://www.cnblogs.com/shanyou/p/6241612.html
/// </summary>
//[Timestamp]//Mysql不允许byte[]类型上标记TimeStamp/RowVersion,这里使用DateTime类型配合标记ConcurrencyCheck达到并发控制
[ConcurrencyCheck]
public DateTime RowVersion { get; set; } /// <summary>
/// 创建时间
/// </summary>
public DateTime CreteTime { get; set; }
}
}

BaseEntity

 using Entity.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text; namespace Entity.Table
{
/// <summary>
/// 商品类
/// </summary>
public class Product : BaseEntity<long>
{
/// <summary>
/// 名称
/// </summary>
[StringLength()]
[Required]
public string Name { get; set; } /// <summary>
/// 描述
/// </summary>
[StringLength()]
[Required]
public string Description { get; set; } /// <summary>
/// 类别
/// </summary>
[Range(, int.MaxValue)]
public int Category { get; set; } /// <summary>
/// 原价
/// </summary>
[Required]
public decimal Price { get; set; } /// <summary>
/// 现价
/// </summary>
public decimal Discount { get; set; }
}
}

Product

  • 在DAL层添加以下引用

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Relational

Pomelo.EntityFrameworkCore.MySql

 using Entity;
using Entity.Table;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace DAL
{
public class ProductContext : DbContext
{
//https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/complex-data-model
public ProductContext(DbContextOptions<ProductContext> options) : base(options)
{
//在此可对数据库连接字符串做加解密操作
} public DbSet<Person> Person { get; set; }
public DbSet<Product> Product { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}

DbContext

  • Service 层

添加引用 Microsoft.EntityFrameworkCore.UnitOfWork

 using System;
using System.Collections.Generic;
using System.Text; namespace Service.ProductService
{
public interface IProductService
{
string Test();
}
}

IProductService

 using Entity.Table;
using Microsoft.EntityFrameworkCore; namespace Service.ProductService
{
public class ProductService : IProductService
{
private readonly IUnitOfWork _unitOfWork;
public ProductService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
} public string Test()
{
var repo = _unitOfWork.GetRepository<Product>();
repo.Insert(new Product
{
Category = ,
Description = "此商品为澳洲代购,买不了吃亏买不了上当",
Discount = (decimal)899.21,
Price = (decimal)98.2,
Name = "澳洲袋鼠粉",
});
_unitOfWork.SaveChanges();//提交到数据库
var result = repo.GetFirstOrDefault()?.Description ?? string.Empty;
return result;
}
}
}

ProductService

  • appsettings.json 的配置
{
"ConnectionStrings": {
"MySqlConnection": "Server=localhost;database=ProjectManager;uid=root;pwd=password;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
  • Startup 的配置
        public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ProductContext>(options =>
options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));//添加Mysql支持 using Microsoft.EnityFrameworkCore services.AddUnitOfWork<ProductContext>();//添加UnitOfWork支持
services.AddScoped(typeof(IProductService), typeof(ProductService));//用ASP.NET Core自带依赖注入(DI)注入使用的类 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
  • 有关数据库迁移命令 (注意要选择保护DbContext项目, 视图 -> 其它窗口 ->  程序包管理器控制台)

add-migration init  (注: 初始化)

update-database

add-migration changeProductTable

remove-migration

如果出现找不到表  __efmigrationshistory, 则运行以下SQL

CREATE TABLE `__EFMigrationsHistory` (
`MigrationId` varchar(95) NOT NULL,
`ProductVersion` varchar(32) NOT NULL,
PRIMARY KEY (`MigrationId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建 __EFMigrationsHistory 表

ef.core Mysql的更多相关文章

  1. EF Core MYSQL 生成表映射配置问题

    Model表 public class Goods { public string ID { get; set; } public string CreatedBy { get; set; } pub ...

  2. EF Core MySql GUID配置方式

    builder.Property(m => m.Id) .HasColumnName("Id") .ForMySQLHasColumnType("char(36)& ...

  3. EF Core 日志跟踪sql语句

    EF Core 日志跟踪sql语句 官方文档链接:https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging 1.新增自定义ILogg ...

  4. .Net EF Core千万级数据实践

    .Net 开发中操作数据库EF一直是我的首选,工作和学习也一直在使用.EF一定程度的提高了开发速度,开发人员专注业务,不用编写sql.方便的同时也产生了一直被人诟病的一个问题性能低下. EF Core ...

  5. Asp.net Core 通过 Ef Core 访问、管理Mysql

    本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1.0.0-preview2-003131 本文分为Window环 ...

  6. MySQL官方.NET Core驱动已出,支持EF Core

    千呼万唤始出来MySQL官方.NET Core驱动已出,支持EF Core. 昨天MySQL官方已经发布了.NET Core 驱动,目前还是预览版,不过功能已经可用. NuGet 地址:https:/ ...

  7. net Core 通过 Ef Core 访问、管理Mysql

    net Core 通过 Ef Core 访问.管理Mysql 本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1. ...

  8. asp.net core + mysql + ef core + linux

    asp.net core + mysql + ef core + linux 以前开发网站是针对windows平台,在iis上部署.由于这次需求的目标服务器是linux系统,就尝试用跨平台的.NET ...

  9. EF Core下利用Mysql进行数据存储在并发访问下的数据同步问题

    小故事 在开始讲这篇文章之前,我们来说一个小故事,纯素虚构(真实的存钱逻辑并非如此) 小刘发工资后,赶忙拿着现金去银行,准备把钱存起来,而与此同时,小刘的老婆刘嫂知道小刘的品性,知道他发工资的日子,也 ...

随机推荐

  1. 【题解】魔板—洛谷P1275。

    话说好久没更博了. 最近学了好多知识懒的加进来了. 有幸认识一位大佬. 让我有了继续更博的兴趣. 但这是一个旧的题解. 我在某谷上早就发过的. 拿过来直接用就当回归了吧. 其实这道题有一个特别关键的思 ...

  2. 我的react+material-ui之路

    在学习react和material-ui时我遇到的问题和解决方法 react要安装得在当前文件夹下面安装, npm命令在当前文件夹执行 npm install -g全局安装, 不会安装在当前包下 np ...

  3. 小E浅谈丨区块链治理真的是一个设计问题吗?

    在2018年6月28日Zcon0论坛上,“区块链治理”这个话题掀起了大神们对未来区块链治理和区块链发展的一系列的畅想. (从左至右,分别为:Valkenburgh,Zooko,Jill, Vitali ...

  4. Mathematica/偏导数/最小二乘法(线性回归)

    a = / a //输出的还是2/123 N[a] //输出的就是小数点 N[a,] //保留三位小数点 Clear[a] Solve[== x^- , x] //结果-3 和 3 Plot[Sin[ ...

  5. vertical-align作用的前提++图片不上下居中

    5.3.2 vertical-align作用的前提 很多人,尤其CSS新手,会问这么一个问题:“为什么我设置了vertical-align却没任何作用?” 因为vertical-align起作用是有前 ...

  6. HTML5 移动端Meta设置

    1.   强制让文档的宽度与设备的宽度保持1:1,并且文档最大的宽度比例是1.0,且不允许用户点击屏幕放大浏览. <meta name="viewport" content= ...

  7. Tensorflow笔记二

    MNIST手写体识别 (Mixed National Institute of Standards and Technology database)的28*28字符识别共0-9类. 在ipython命 ...

  8. linux设置环境变量(这里以hive为例给大家举例)

    1.进入: cd /export/servers/hive/bin/ -rwxr-xr-x. 1 root root 1031 Apr 30 2015 beeline-rw-r--r--. 1 roo ...

  9. vs 修改活动解决方案配置后无法调试,不生成pdb文件,“当前不会命中断点 还没有为该文档加载任何符号” 解决方法

    修改vs的活动解决配置后无法进行调试,比如在Release.Debug之后新增一个TEST,切换到test后就无法进行调试. 修改一下 项目属性->生成->高级 中“调试信息”改为 ful ...

  10. pip 源

    pip使用过程中的痛苦,大家相必都已经知道了,目前豆瓣提供了国内的pypi源,源包相对会略有延迟,但不影响基本使用. pip install some-package -i https://pypi. ...