在项目中使用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 查看信息-磁盘分区&网络

    磁盘和分区 1.查看挂接的分区状态 2.查看所有交换分区 3.查看启动时IDE设备检测状况 网络 1.查看网络接口属性 2.查看防火墙设置 3.查看路由表 4.查看所有监听端口 5.查看所有已经建立的 ...

  2. python基本数据类型之字符串(二)

    python基本数据类型之字符串(二) 替换方法 python中字符串的替换方法主要有:center.rjust\ljust.expandtabs.format\format_map(格式化).str ...

  3. mac virtualbox 安装

    在Mac上装virtualbox提示安装失败!!! 安全性与隐私的通用下点击允许!!!

  4. Delphi Excel导入 的通用程序转载

    Delphi Excel导入 的通用程序 (-- ::)转载▼ 标签: it 分类: Delphi相关 步骤: 连excel(自己知道其格式,最好是没个字段在数据一一对应) 读excel数据,填入到数 ...

  5. 背水一战 Windows 10 (85) - 文件系统: 获取文件夹和文件, 分组文件夹, 排序过滤文件夹和文件, 搜索文件

    [源码下载] 背水一战 Windows 10 (85) - 文件系统: 获取文件夹和文件, 分组文件夹, 排序过滤文件夹和文件, 搜索文件 作者:webabcd 介绍背水一战 Windows 10 之 ...

  6. 重新编译安装swoole支持OpenSSL

    1.下载:wget http://pecl.php.net/get/swoole-1.9.22.tgz 2.解压:tar zxvf swoole-1.9.22.tgz 3.扩展模块:cd swoole ...

  7. Learning WCF:Life Cycle of Service instance

    示例代码下载地址:WCFDemo1Day 概述 客户端向WCF服务发出请求后,服务端会实例化一个Service对象(实现了契约接口的对象)用来处理请求,实例化Service对象以及维护其生命周期的方式 ...

  8. 谷歌浏览器怎么FQ(一)(想使用谷歌浏览器应用商城的小伙伴这边看)

    谷歌浏览器的应用商城里本身有很多不错的扩展程序和插件,比如Wappalyzer(能够识别某个网站用的什么框架和库)广告终结者(能屏蔽大部分浮动,弹窗,甚至视频广告)等 但是谷歌因为某些原因需要FQ以后 ...

  9. [CocoaPods]CocoaPods安装详解

    安装CocoaPods之前先安装ruby: 1.安装ruby ruby官网rubygems.org已被屏蔽,替换当前镜像是否为国内镜像. $gem sources --add https://gems ...

  10. linux下静态链接库和动态链接库

    关于链接库的知识,网上太多资料了,但是并不代表我很熟悉.今天遇到了 一个问题,就是由于静态链接库和ubuntu系统不兼容导致的,虽然花了点时间才搞定 但是,其中暴露的问题也不少. 没有区分好静态链接库 ...