在项目中使用EF Core还是比较容易的,在这里我们使用的版本是EF Core 2.2.

1.使用nuget获取EF Core包

这个示例项目使用的是SQLSERVER,所以还需要下载Microsoft.EntityFrameworkCore.SqlServer这个包

2.在Startup类的Configure方法中设置默认的数据库访问连接字符串

 //数据库连接字符串
Framework.Core.Configuration.AddItem("ConnectionStrings",Configuration.GetSection("ConnectionStrings").Value);

PS:我这里并没有使用DI注入的方式去使用EFCORE的实例,还是使用传统的New的方式,所以并不需要在Startup中进行注入

3.在Mango.EFCore类库项目中创建一个EFDbContext类继承自DbContext我们就能在其它地方使用EFCore了,代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Mango.Entity;
namespace Mango.Framework.EFCore
{
    public class EFDbContext : DbContext
    {
        public EFDbContext()
        {

        }

        public EFDbContext(DbContextOptions<EFDbContext> options): base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(Core.Configuration.GetItem("ConnectionStrings"));
            }
        }
        #region Entity DbSet<>
        public virtual DbSet<m_WebSiteConfig> m_WebSiteConfig { get; set; }
        public virtual DbSet<m_PostsRecords> m_PostsRecords { get; set; }
        public virtual DbSet<m_WebSiteNavigation> m_WebSiteNavigation { get; set; }

        public virtual DbSet<m_Sms> m_Sms { get; set; }

        public virtual DbSet<m_ManagerAccount> m_ManagerAccount { get; set; }
        public virtual DbSet<m_ManagerMenu> m_ManagerMenu { get; set; }
        public virtual DbSet<m_ManagerPower> m_ManagerPower { get; set; }
        public virtual DbSet<m_ManagerRole> m_ManagerRole { get; set; }
        public virtual DbSet<m_Message> m_Message { get; set; }
        public virtual DbSet<m_Navigation> m_Navigation { get; set; }
        public virtual DbSet<m_NavigationClassify> m_NavigationClassify { get; set; }
        public virtual DbSet<m_Posts> m_Posts { get; set; }
        public virtual DbSet<m_PostsChannel> m_PostsChannel { get; set; }
        public virtual DbSet<m_PostsAnswer> m_PostsAnswer { get; set; }
        public virtual DbSet<m_PostsAnswerRecords> m_PostsAnswerRecords { get; set; }
        public virtual DbSet<m_PostsAttention> m_PostsAttention { get; set; }
        public virtual DbSet<m_PostsComments> m_PostsComments { get; set; }
        public virtual DbSet<m_PostsCommentsRecords> m_PostsCommentsRecords { get; set; }
        public virtual DbSet<m_PostsTags> m_PostsTags { get; set; }
        public virtual DbSet<m_User> m_User { get; set; }
        public virtual DbSet<m_UserGroup> m_UserGroup { get; set; }
        public virtual DbSet<m_UserGroupMenu> m_UserGroupMenu { get; set; }
        public virtual DbSet<m_UserGroupPower> m_UserGroupPower { get; set; }
        #endregion
    }
}

4.接下来我们在Mango.Repository仓储类库项目中使用EFCore,代码示例如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Mango.Framework.EFCore;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
namespace Mango.Repository
{
    public class AuthorizationRepository
    {
        private EFDbContext _dbContext = null;
        public AuthorizationRepository()
        {
            _dbContext = new EFDbContext();
        }
        /// <summary>
        /// 根据用户组获取权限
        /// </summary>
        /// <param name="GroupId"></param>
        /// <returns></returns>
        public List<Models.UserGroupPowerModel> GetPowerData(int groupId)
        {
            var query = from ugp in _dbContext.m_UserGroupPower
                        join ugm in _dbContext.m_UserGroupMenu
                        on ugp.MId equals ugm.MId
                        where ugp.GroupId == groupId
                        select new Models.UserGroupPowerModel()
                        {
                            GroupId=ugp.GroupId.Value,
                            MId=ugm.MId.Value,
                            MName=ugm.MName,
                            AreaName=ugm.AreaName,
                            ControllerName=ugm.ControllerName,
                            ActionName=ugm.ActionName
                        };
            return query.ToList();
        }
    }
}

以上介绍了EFCore的基本使用示例,其实我们平常在项目中会将一些常用的增删改统一封装起来,我们创建一个CommonRepository类,代码如下:

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using Mango.Framework.EFCore;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace Mango.Repository
{
    public class CommonRepository
    {
        private EFDbContext _dbContext = null;
        public CommonRepository()
        {
            _dbContext = new EFDbContext();
        }
        /// <summary>
        /// 添加记录
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add<TEntity>(TEntity entity) where TEntity:class
        {
            _dbContext.Add(entity);
            ;
        }
        /// <summary>
        /// 根据Id获取指定记录
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="Id"></param>
        /// <returns></returns>
        public TEntity Find<TEntity>(int Id) where TEntity : class
        {
            return _dbContext.Find<TEntity>(Id);
        }
        /// <summary>
        /// 更新记录
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="IsFind"></param>
        /// <returns></returns>
        public bool Update<TEntity>(TEntity entity, bool isFind) where TEntity : class
        {
            _dbContext.Update(entity);

            ;
        }
        /// <summary>
        /// 更新记录(修改指定的列)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public bool Update<TEntity>(TEntity entity) where TEntity : class
        {
            _dbContext.Entry(entity).State = EntityState.Unchanged;
            //
            Type type= entity.GetType();
            //处理实体类属性
            PropertyInfo[] properties = type.GetProperties();
            foreach (var property in properties)
            {
                object value = property.GetValue(entity, null);
                var key = property.GetCustomAttribute<KeyAttribute>();
                if (value != null&& key==null)
                {
                    _dbContext.Entry(entity).Property(property.Name).IsModified = true;
                }
            }
            ;
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete<TEntity>(TEntity entity) where TEntity : class
        {
            _dbContext.Remove(entity);
            ;
        }
    }
}

PS:这篇EFCore的基础使用就到此为止,详情请下载源代码查看,下一篇将讲解如何基于EFCore进行一些基础的扩展

使用Asp.Net Core MVC 开发项目实践[第二篇:EF Core]的更多相关文章

  1. 使用Asp.Net Core MVC 开发项目实践[第一篇:项目结构说明]

    先从下图看整体项目结构: Mango.Manager: 为后台管理项目 Mango.Web: 为前台项目 Mango.Framework.Core: 为常用的基础操作类项目 Mango.Framewo ...

  2. 使用Asp.Net Core MVC 开发项目实践[第五篇:缓存的使用]

    项目中我们常常会碰到一些数据,需要高频率用到但是又不会频繁变动的这类,我们就可以使用缓存把这些数据缓存起来(比如说本项目的导航数据,帖子频道数据). 我们项目中常用到有Asp.Net Core 本身提 ...

  3. 使用Asp.Net Core MVC 开发项目实践[第三篇:基于EF Core的扩展]

    上篇我们说到了EFCore的基础使用,这篇我们将讲解下基于EFCore的扩展. 我们在Mango.Framework.EFCore类库项目中创建一个类名EFExtended的扩展类,并且引入相关的命名 ...

  4. 使用Asp.Net Core MVC 开发项目实践[第四篇:基于EF Core的扩展2]

    上篇我们说到了基于EFCore的基础扩展,这篇我们讲解下基于实体结合拉姆达表达式的自定义更新以及删除数据. 先说下原理:其实通过实体以及拉姆达表达式生成SQL语句去执行 第一种更新扩展: 自定义更新字 ...

  5. ASP.NET自定义控件组件开发 第一章 第二篇 接着待续

    原文:ASP.NET自定义控件组件开发 第一章 第二篇 接着待续 ASP.NET自定义控件组件开发 第一章 第二篇 接着待续 很感谢大家给我的第一篇ASP.NET控件开发的支持!在写这些之前,我也看了 ...

  6. 《ASP.NET Core应用开发入门教程》与《ASP.NET Core 应用开发项目实战》正式出版

    “全书之写印,实系初稿.有时公私琐务猬集,每写一句,三搁其笔:有时兴会淋漓,走笔疾书,絮絮不休:有时意趣萧索,执笔木坐,草草而止.每写一段,自助覆阅,辄摇其首,觉有大不妥者,即贴补重书,故剪刀浆糊乃不 ...

  7. Pro ASP.NET Core MVC 第6版 第二章(前半章)

    目录 第二章 第一个MVC 应用程序 学习一个软件开发框架的最好方法是跳进他的内部并使用它.在本章,你将用ASP.NET Core MVC创建一个简单的数据登录应用.我将它一步一步地展示,以便你能看清 ...

  8. 创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

    创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表 创建数据模型类(POCO类) 在Models文件夹下添 ...

  9. Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类

    本文目录 1.  前沿 2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装 3.XmlHelper快速操作xml文档 4.Serializatio ...

随机推荐

  1. linux 查看机器cpu核数

    CPU总核数 = 物理CPU个数 * 每颗物理CPU的核数 总逻辑CPU数 = 物理CPU个数 * 每颗物理CPU的核数 * 超线程数 查看CPU信息(型号) [root@AAA ~]# cat /p ...

  2. C++ MFC棋牌类小游戏day2

    反思了一下昨天的设计,觉得略有不足,我决定把棋盘做成单例模式.这样的话需要重新设计棋盘类,emmm,是新建棋盘类. Baord类 成员变量: Location  coordinate;//棋子坐标 b ...

  3. 【慕课网实战】Spark Streaming实时流处理项目实战笔记十三之铭文升级版

    铭文一级: 第10章 Spark Streaming整合Kafka spark-submit \--class com.imooc.spark.KafkaReceiverWordCount \--ma ...

  4. windows 批处理语言学习

    程序员应该根植于心的一个理念是:重复的工作交给代码.windows上的批处理脚本就是这种理念的体现. 批处理bat能做的事很多,自动配置vs工程中的代码依赖环境,调用其它程序处理数据.自动编译代码等等 ...

  5. 用Python进行有进度条的π计算

    1.tqdm是一个强大的终端进度条工具,我利用pip获取tqdm函数库. 2编写代码 2.1进行π的计算 from random import random from math import sqrt ...

  6. WebRTC 学习之 WebRTC 简介

    本文使用的WebRTC相关API都是基于Intel® Collaboration Suite for WebRTC的. 相关文档链接:https://software.intel.com/sites/ ...

  7. Swift5 语言指南(十二) 属性

    属性将值与特定类,结构或枚举相关联.存储的属性将常量和变量值存储为实例的一部分,而计算属性则计算(而不是存储)值.计算属性由类,结构和枚举提供.存储的属性仅由类和结构提供. 存储和计算属性通常与特定类 ...

  8. Shell-2--输入输出重定向

    自己写一下吧,免得又忘了,被人问到,被鄙视 0 表示标准输入, 1 表示标准输出 , 2 表示标准错误输出 一个 > 表示已覆盖的方式把命令的正确执行重定向到文件 两个 >> 表示是 ...

  9. php省市联动实现

    设计模式:ajax实现,数据库格式:id,name,parent_id 数据库: CREATE TABLE IF NOT EXISTS `city` ( `id` ) NOT NULL AUTO_IN ...

  10. LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy

    要求:求二叉树的深度(二叉树的深度为最远叶子节点到根节点的距离,即根节点到最远叶子节点的距离) Given a binary tree, find its maximum depth. The max ...