在项目中使用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. 最长公共子序列(LCS)最长递增子序列(LIS)

    #include<cstring>#include<iostream>#include<stack>#include <algorithm>using ...

  2. 学习newton raphson and back eluer

    % % time step https://ww2.mathworks.cn/matlabcentral/answers/184200-newton-raphson-loop-for-backward ...

  3. Linux下设置快捷键

    以设置终端为例,进入Settings>>Keyboard>>Custom Shortcuts,点左下脚的+号,Name栏填入Treminal,command栏填入gnome-t ...

  4. win7 装docker

    Win7安装Docker 主要是装这个 ,官网没有win7版本 Docker Toolbox on Windows

  5. 使用CefSharp在.Net程序中嵌入Chrome浏览器(一)——简介

    有的时候,我们需要在程序中嵌入Web浏览器,其实.Net Framework中本身就提供了WebBrowser控件,本身这个是最简单易用的方案,但不知道是什么原因,这个控件在浏览网页的时候有些莫名的卡 ...

  6. 595. Big Countries --- SQL related from leetcode

    595. Big Countries There is a table World +-----------------+------------+------------+------------- ...

  7. 学习WPF——使用Font-Awesome图标字体(一)

    一.运行效果图 二.图标字体文件下载 http://fontawesome.dashgame.com/(这个网址可以下载图标字体文件) http://www.fontawesome.com.cn/(这 ...

  8. 记web模拟手机环境已经微信开发者工具中可正常运行,实体机运行报错问题

    问题描述: 有个手机微信OA的项目 用户信息采用cookie方式保存.发布后使用chorme浏览器进行模拟访问测试发现一切运行顺畅,使用微信开发者工具进行测试也一切正常. 采用实体机进行测试时,用微信 ...

  9. sku 和 spu

    https://www.jianshu.com/p/867429702d5a     里面的图片挺好的

  10. Yii2 Template 组件框架集封装

    项目简介: Yii2_Template是一个“提供大多数PHP常用的组件去集合成的一套基于Yii2的项目框架”. 该项目是一款秉着提高 开发效率.降低开发成本,遵循高拓展,高可用的原则的进行开发的框架 ...