使用Asp.Net Core MVC 开发项目实践[第二篇:EF Core]
2024-10-11 00:36:32
在项目中使用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进行一些基础的扩展
最新文章
- java之多线程 二
- [常见问题]在Linux下执行Redis命令不起作用.
- SQL Server配置管理器的“别名”功能好处,实现内外网统一以及加了端口号导致的限制
- GPS accuracy in Android
- mustache.js渲染带事件的模板
- (转)配置Website的IIS时遇到的问题与解决方法
- sql分类及基本sql操作,校对规则(mysql学习笔记二)
- .NET中的标识符、关键字 以及 .NET中的命名规范
- 几个检查当前运行的LINUX是在VM还是在实体机中的方法
- 逻辑卷lvm创建、扩展、缩小
- 判断mine类型
- curl HTTP Header
- grid布局笔记学习一之父元素(容器)
- 自定义el标签
- MySQL binlog_format (Mixed,Statement,Row)[转]
- MD5加密和彩虹表
- Andriod——手机尺寸相关的概念 +尺寸单位+关于颜色
- LINUX内核分析第五周学习总结——扒开应用系统的三层皮(下)
- Intellij IDEA 使用spring-boot-devtools无效解决办法一
- centos 升级linux内核
热门文章
- git stash错误小记
- MySQL InnoDB配置并发线程( innodb_thread_concurrency)
- canvas画圆环
- selenium_unittest框架,TestCase引用
- 14. The Realities of Telecommuting 远程办公的现状
- vue-学习系列之vue双向绑定原理
- windows下angularJs环境搭建和遇到的问题解决
- verilog 有符号数(2转)
- str相关操作
- 图像质量评价方法PSNR+SSIM&;&;评估指标SROCC,PLCC