Entityframework core where条件,执行的sql字符串及其结果

Posted

技术标签:

【中文标题】Entityframework core where条件,执行的sql字符串及其结果【英文标题】:Entityframework core where condition, sql string that executed and its result 【发布时间】:2021-11-26 12:24:57 【问题描述】:

我实现了一个 api 并使用了 EF 核心。

我有一个复杂的结构,它的核心实体是一个我称之为项目的实体。 我应该说我使用 EF Core 作为 DB First。然后我首先创建了我的数据库,之后我使用“Scaffold-Database”在代码中创建了我的模型。

项目的模型是:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace myProj_Model.Entities

    public partial class Projects
    
        public Projects()
        
            Boreholes = new HashSet<Boreholes>();
            ProjectsWorkAmounts = new HashSet<ProjectsWorkAmount>();
            Zones = new HashSet<Zones>();
        

        public long Id  get; set; 
        public string Number  get; set; 
        public string Name  get; set; 
        public string Description  get; set; 
        public string ClientName  get; set; 
        public int? NoOfRecord  get; set; 
        public byte[] Logo  get; set; 
        public int? LogoWidth  get; set; 
        public int? LogoHeight  get; set; 
        public string Version  get; set; 
        public byte? Revision  get; set; 
        public byte? WorkValueIsLimit  get; set; 
        public long? CreatedBy  get; set; 
        public DateTime? CreatedDate  get; set; 
        public long? ModifiedBy  get; set; 
        public DateTime? ModifiedDate  get; set; 

        public virtual Users CreatedBy_User  get; set; 
        public virtual Users ModifiedBy_User  get; set; 
        public virtual ProjectsDrillingLog ProjectsDrillingLog  get; set; 
        public virtual ProjectsDutchCone ProjectsDutchCone  get; set; 
        public virtual ProjectsGap ProjectsGap  get; set; 
        //public virtual ProjectsLogDrafting ProjectsLogDrafting  get; set; 
        public virtual ProjectsRole ProjectsRole  get; set; 
        public virtual ProjectsUnc ProjectsUnc  get; set; 
        public virtual ICollection<Boreholes> Boreholes  get; set; 
        public virtual ICollection<ProjectsWorkAmount> ProjectsWorkAmounts  get; set; 
        public virtual ICollection<Zones> Zones  get; set; 
    

我再次提到模型是由“脚手架”命令创建的。 CRUD 操作由 GenericRepository 处理:

using geotech_Tests_Model.Entities;
using geotech_Tests_Model.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace myProj_Model.Repositories

    public class GenericRepository<T> : IGenericRepository<T> where T : class
    
        protected geotechContext _context  get; set; 
        public GenericRepository(geotechContext context)
        
            this._context = context;
        

        public void Add(T entity)
        
            try
            
                _context.Set<T>().Add(entity);
                _context.SaveChanges();
            
            catch (Exception eXp)
            
                string Myname = eXp.Message;
            
        

        public void AddRange(IEnumerable<T> entities)
        
            try
            
                _context.Set<T>().AddRange(entities);
                _context.SaveChanges();
            
            catch (Exception eXp)
            
                string Myname = eXp.Message;
            
        

        public void Update(T entity)
        
            try
            
                _context.Set<T>().Update(entity);
                _context.SaveChanges();
            
            catch (Exception eXp)
            
                string Myname = eXp.Message;
            
        

        public void UpdateRange(IEnumerable<T> entities)
        
            try
            
                _context.Set<T>().UpdateRange(entities);
                _context.SaveChanges();
            
            catch (Exception eXp)
            
                string Myname = eXp.Message;
            
        

        public IQueryable<T> Find()
        
            return _context.Set<T>().AsQueryable();
        

        public List<T> Find(FilterStruct filterstruct)
        
            Expression<Func<T, bool>> myExpresion = Expresion(filterstruct);

            return _context.Set<T>().AsQueryable().IgnoreAutoIncludes().Where(myExpresion).ToList ();
        

        public T GetById(long id)
        
            return _context.Set<T>().Find(id);
        

        public void Remove(T entity)
        
            try
            
                _context.Set<T>().Remove(entity);
                _context.SaveChanges();
            
            catch (Exception eXp)
            
                string Myname = eXp.Message;
            
        

        public void RemoveRange(IEnumerable<T> entities)
        
            try
            
                _context.Set<T>().RemoveRange(entities);
                _context.SaveChanges();
            
            catch (Exception eXp)
            
                string Myname = eXp.Message;
            
        

        public Expression< Func<T, bool>> Expresion(FilterStruct filters)
        

            //IQueryable<T> myQry = _context.Set<T>().AsQueryable<T>();
            //IQueryable<T> myQryFilter = _context.Set<T>().AsQueryable<T>();


            List<QueryStruct> queries = filters.Queries;

            Expression predicateBody = null;

            ParameterExpression myExp = Expression.Parameter(typeof(T), typeof(T).Name);

            if (queries != null)
            
                foreach (QueryStruct query in queries)
                
                    Expression e1 = null;
                    Expression left = Expression.Property(myExp, typeof(T).GetProperty(query.columnName));
                    Type actualType = Type.GetType(left.Type.FullName);
                    var myValue = Convert.ChangeType(query.value, actualType);

                    Expression right = Expression.Constant(myValue);

                    e1 = ApplyOperand(left, right, query.operatorName);

                    if (predicateBody == null)
                        predicateBody = e1;
                    else
                    
                        predicateBody = ApplyAndOr(predicateBody, e1, query.AndOr);
                    

                
            


            //var p = Expression.Parameter(typeof(T), typeof(T).Name);
            //if (predicateBody == null) predicateBody = Expression.Constant(true);
            //MethodCallExpression whereCallExpression = Expression.Call(
            //typeof(Queryable),
            //"Where", new Type[]  myQryFilter.ElementType ,
            //myQryFilter.Expression, Expression.Lambda<Func<T>, bool> > (predicateBody, myExp));

            var Lambda = Expression.Lambda <Func<T, bool>>(predicateBody, myExp);
            return Lambda;
        

        public static Expression ApplyOperand(Expression Left, Expression Rigth, OperandEnum Operand)
        
            Expression result = null;
            switch (Operand)
            
                case (OperandEnum.Equal):
                    
                        result = Expression.Equal(Left, Rigth);
                        break;
                    
                case (OperandEnum.NotEqual):
                    
                        result = Expression.NotEqual(Left, Rigth);
                        break;
                    
                case (OperandEnum.GreaterThan):
                    
                        result = Expression.GreaterThan(Left, Rigth);
                        break;
                    
                case (OperandEnum.GreaterThanOrEqual):
                    
                        result = Expression.GreaterThanOrEqual(Left, Rigth);
                        break;
                    
                case (OperandEnum.LessThan):
                    
                        result = Expression.LessThan(Left, Rigth);
                        break;
                    
                case (OperandEnum.LessThanOrEqual):
                    
                        result = Expression.LessThanOrEqual(Left, Rigth);
                        break;
                    
            

            return result;


        

        public static Expression ApplyAndOr(Expression Left, Expression Rigth, AndOrEnum AndOr)
        
            Expression result = null;
            switch (AndOr)
            
                case (AndOrEnum.And):
                    
                        result = Expression.And(Left, Rigth);
                        break;
                    
                case (AndOrEnum.AndAlso):
                    
                        result = Expression.AndAlso(Left, Rigth);
                        break;
                    
                case (AndOrEnum.AndAssign):
                    
                        result = Expression.AndAssign(Left, Rigth);
                        break;
                    
                case (AndOrEnum.Or):
                    
                        result = Expression.Or(Left, Rigth);
                        break;
                    
                case (AndOrEnum.OrAssign):
                    
                        result = Expression.OrAssign(Left, Rigth);
                        break;
                    
                case (AndOrEnum.OrElse):
                    
                        result = Expression.OrElse(Left, Rigth);
                        break;
                    
            

            return result;


        





    

我的 Startup.cs 中有这样的 ConfigureServices:

    public void ConfigureServices(IServiceCollection services)


    services.AddCors(options =>
    
        options.AddPolicy(_appCorsPolicy,
            builder =>
            
                builder.WithOrigins("http://127.0.0.1:23243")
                .AllowAnyHeader();
                //.AllowAnyMethod();
            );
    );

    //****************************************************************************************
    services.AddControllers();

    services.AddControllersWithViews().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

    services.Configure<IISOptions>(options =>
    
    );
    services.AddAutoMapper(typeof(Startup));
    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    
        c.SwaggerDoc("v1", new OpenApiInfo  Title = "Organization, .Net Core", Version = "V 01" );

        // Set the comments path for the Swagger JSON and UI.
        var xmlFile = $"Assembly.GetExecutingAssembly().GetName().Name.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

        c.IncludeXmlComments(xmlPath);
    );

    string connectionStr = Configuration.GetConnectionString("DefaultConnection");

    services.AddDbContext<geotechContext>(options => options.UseLazyLoadingProxies().UseSqlServer(connectionStr));

    //Farzin
    services.Add(new ServiceDescriptor(typeof(IProjectsService), typeof(ProjectsService), ServiceLifetime.Scoped));
    
    //  AddServicesHere


之后,我的项目实体有了一个服务类。 GetById 是我在 Service 类中拥有的几个函数之一。

    public EventResult GetById(long id)

    EventResult result = new EventResult();
    //result.Data = service.GetById (id);
    result.Data = service.Find().IgnoreAutoIncludes().Where(a => (a.Id == id)).FirstOrDefault();
    return result;

现在的主要问题是,响应时间相当长。我跟踪每一行代码,甚至是执行的 sql 命令。 Sql profiler 显示发送到 SqlServer 的 sql 命令。命令是:

    exec sp_executesql N'SELECT TOP(1) [g].[Id], [g].[gtp_ClientName], [g].[CreatedBy], [g].[CreatedDate], [g].[gtP_Description], [g].[gtp_Logo], [g].[gtp_LogoHeight], [g].[gtp_LogoWidth], [g].[ModifiedBy], [g].[ModifiedDate], [g].[gtP_Name], [g].[gtp_NoOfRecord], [g].[gtP_ProjectNumber], [g].[gtp_Revision], [g].[gtp_Version], [g].[gtp_WorkValueIsLimit]
FROM [gt_Projects] AS [g]
WHERE [g].[Id] = @__id_0',N'@__id_0 bigint',@__id_0=1

没有任何关系,这个sql的执行结果是一个简单的行,没有任何额外的数据。但我大摇大摆地得到的答案是包含所有相关数据的复杂记录。

Result of query

我希望招摇的结果是这样的

Expected Result

但结果是这样的:

    
  "errorNumber": 0,
  "errorMessage": "",
  "eventId": 0,
  "data": 
    "createdBy_User": 
      "projectsRoleId1": null,
      "boreholeCreatedByNavigations": [],
      "boreholeModifiedByNavigations": [],
      "boreholeTypeCreatedByNavigations": [
        
          "boreholes": [],
          "id": 1,
          "abbriviation": "P",
          "name": "Primary",
          "description": "Primary Boreholes",
          "order": 1,
          "color": null,
          "createdBy": 1,
          "createdDate": "1400-05-27T00:00:00",
          "modifiedBy": 1,
          "modifiedDate": "1400-05-27T00:00:00"
        
      ],
      "boreholeTypeModifiedByNavigations": [
        
          "boreholes": [],
          "id": 1,
          "abbriviation": "P",
          "name": "Primary",
          "description": "Primary Boreholes",
          "order": 1,
          "color": null,
          "createdBy": 1,
          "createdDate": "1400-05-27T00:00:00",
          "modifiedBy": 1,
          "modifiedDate": "1400-05-27T00:00:00"
        
      ],
      "boreholesWorkAmountCreatedByNavigations": [],
      "boreholesWorkAmountModifiedByNavigations": [],
      "dailyActivityDaCoSupervisorNavigations": [],
      "dailyActivityDaSpecialistNavigations": [],
      "dailyActivityDaSupervisorNavigations": [],
      "dailyActivityDaTechnision01Navigations": [],
      "dailyActivityDaTechnision02Navigations": [],
      "created_Projects": [
        
          "projectsDrillingLog": null,
          "projectsDutchCone": null,
          "projectsGap": null,
          "projectsRole": null,
          "projectsUnc": null,
          "boreholes": [],
          "projectsWorkAmounts": [],
          "zones": [],
          "id": 2,
          "number": "001",
          "name": "Yes",
          "description": "ss",
          "clientName": "ss",
          "noOfRecord": 1,
          "logo": null,

.........
.........
        "id": 5,
        "workActivity": 6,
        "project": 1,
        "activityPredicted": 5,
        "activityActual": null,
        "startDatePredicted": null,
        "endDatePredicted": null,
        "startDateActual": null,
        "endDateActual": null,
        "createdBy": null,
        "createdDate": null,
        "modifiedBy": null,
        "modifiedDate": null
      
    ],
    "zones": [],
    "id": 1,
    "number": "001",
    "name": "No",
    "description": "ss",
    "clientName": "ss",
    "noOfRecord": 1,
    "logo": null,
    "logoWidth": 11,
    "logoHeight": 11,
    "version": "1",
    "revision": 1,
    "workValueIsLimit": 1,
    "createdBy": 1,
    "createdDate": "1400-06-01T00:00:00",
    "modifiedBy": 1,
    "modifiedDate": "1400-06-01T00:00:00"
  

答案包含近 4700 行数据,这发生在我的数据库几乎是空的时候。 我不知道为什么以及我应该怎么做才能得到我的预期结果作为答案。

【问题讨论】:

你是对的。我从我的 Db 设置中删除了 .UseLazyLoadingProxies() ,现在一切正常。非常感谢。 【参考方案1】:

我注意到你有.UseLazyLoadingProxies(),这意味着你可以从数据库中加载一些数据,然后通过访问属性触发加载更多数据;例如,您只下载了一个项目,但一旦您尝试访问其 Boreholes 集合,该访问将触发另一个查询,如 SELECT * FROM Boreholes WHERE projectId = (whatever the current project id is) 以在返回之前填充钻孔集合..

这意味着当序列化程序枚举您的起始Project 的属性时,寻找可以序列化的数据,而不是在访问某些相关数据的导航属性时获取“null”或“空”,它是序列化程序这会触发每个相关实体的数据库查找......然后它会序列化所有这些相关实体并枚举 它们的道具会触发更多查找。

一开始只是一个项目,然后滚雪球加载每个相关实体上下树,甚至可能是整个数据库,只是因为您要求序列化程序将项目对象转换为 json..


删除延迟加载代理功能将停止该功能,但项目的其他部分不会在访问时自动加载数据;您对此所做的可能是关于如何加载相关数据的更广泛的设计决策..

【讨论】:

我不需要自动加载数据。如果我需要项目数据的其他部分,那么我使用 Include。无论如何,我感谢你的帮助。非常感谢。 @FarzinSotoodi 那么你必须关闭你的延迟加载。那么你每次都会得到不必要的信息

以上是关于Entityframework core where条件,执行的sql字符串及其结果的主要内容,如果未能解决你的问题,请参考以下文章

从零开始学 ASP.NET Core 与 EntityFramework Core 目录

EntityFramework Core 中的映射继承

带有标识 2 和 EntityFramework 6(Oracle)的 ASP.NET Core MVC

EntityFramework Core技术线路(EF7已经更名为EF Core,并于2016年6月底发布)

.Net Core005EntityFramework的使用

.Net Core005EntityFramework的使用