繁体   English   中英

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

[英]Entityframework core where condition, sql string that executed and its result

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

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

该项目的model是:

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; }
    }
}

我再次提到 model 是由“脚手架”命令创建的。 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}

}

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

    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 探查器显示发送到 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 的执行结果是一个没有任何附加数据的简单行。 但是我在 swagger 中得到的答案是包含所有相关数据的复杂记录。

查询结果

我希望 swagger 的结果是这样的

预期结果

但结果是这样的:

    {
  "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 行数据,这是在我的数据库几乎为空时发生的。 我不知道为什么以及我应该做什么,以获得我预期的结果作为答案。

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

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

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM