返回连接两个表的IQueryable

时间:2019-07-10 21:05:18

标签: c# linq entity-framework-core

此服务方法将返回IQueryable<Vehicle>

public IQueryable<Vehicle> GetVehicles()
{
    return
        from v in _context.Vehicles
        where
            v.Schedule == true
            && v.Suspend == false
        select v;
}

如果我想在查询中包括另一个表:

public IQueryable<Vehicle> GetVehicles()
{

    return
        from v in _context.Vehicles
        join si in _context.ServiceIntervals on v.Id equals si.VehicleId into loj
        from rs in loj.DefaultIfEmpty()
        where
            v.Schedule == true
            && v.Suspend == false
        select new { vehicle = v, repair = rs };

}

正确的IQueryable<T>返回类型是什么? IQueryable<{vehicle,repair}>不正确。

是否有更好的方式编写select语句?

**编辑**

我希望保持简单,但我认为澄清是有用的。

ServiceIntervals实际上是一个IQueryable<T>,它引用了另一个SQL DB中的表值函数:

public IQueryable<ServiceInterval> ServiceIntervals(DateTime startingDate, DateTime endingDate) =>
    Query<ServiceInterval>().FromSql($@"
        SELECT *
        FROM OtherDatabase.Dbo.ServiceIntervals({startingDate}, {endingDate})"
    );

原始查询实际上包括日期:

...
_context.ServiceIntervals(DateTime.Now.Date,DateTime.Now.Date)
...

因此,我认为ServiceIntervals不能作为导航属性公开在Vehicle实体上。

2 个答案:

答案 0 :(得分:3)

在LINQ中执行def process(context: Context, elements: Iterable[IN], out: Collector[OUT])会创建一个匿名类型,根据定义,该类型是匿名的,不能用作返回类型。如果要返回此变量,则必须为其创建一个类型。

select new {}

您可以在自定义DTO类中更改类型和变量名称以匹配public class VehicleServiceDTO { public Vehicle Vehicle { get; set; } public ServiceInterval Repair { get; set; } } public IQueryable<VehicleServiceDTO> GetVehicles() { return from v in _context.Vehicles join si in _context.ServiceIntervals on v.Id equals si.VehicleId into loj from rs in loj.DefaultIfEmpty() where v.Schedule == true && v.Suspend == false select new VehicleServiceDTO() { Vehicle = v, Repair = rs }; } 的类型(我假设它被称为_context.ServiceIntervals)。

答案 1 :(得分:2)

我不一定认为您不应该在这里使用导航属性。它们是虚拟的,并基于Linq语句生成查询。

在这种情况下,我也不认为单独的DTO模型有意义。由于您提到了导航属性,因此我假设您的关系是一对多的。我的猜测是,应该对车辆进行修理。如果真是这样,那么GroupJoin可能会起作用。 EF支持它:https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities

我添加了一个属性,用于维修车辆

public IEnumerable<ServiceInterval> RepairsToSchedule { get; set; }

然后查询最终看起来像这样:

public static IQueryable<Vehicle> GetVehicles()
{
    return _context.Vehicles
        .Where(v => v.Schedule && !v.Suspend)
        .GroupJoin(_context.ServiceIntervals,
            v => v.Id,
            si => si.VehicleId,
            (v, si) => SetServiceIntervals(v, si));
}

我使用下面的静态方法将 ServiceIntervals 添加到车辆

private static Vehicle SetServiceIntervals(Vehicle v, IEnumerable<ServiceInterval> si)
{
    v.RepairsToSchedule = si;
    return v;
}

整个源代码如下: 已编辑:针对两个单独的数据库进行了调整(请注意,在同一服务器上)

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace StackoverFlow
{
    class Program
    {
        private static FakeDatabaseContext _context = new FakeDatabaseContext();
        private static FakeDatabaseContext2 _context2 = new FakeDatabaseContext2();

        static void Main(string[] args)
        {
            CleanContext();
            LoadContext();

            foreach (var vehicle in GetVehicles())
            {
                Console.WriteLine(JsonConvert.SerializeObject(vehicle, Formatting.Indented));
                Console.WriteLine();
            }
            Console.ReadKey();
        }

        public static IQueryable<Vehicle> GetVehicles()
        {
            return _context.Vehicles
                .Where(v => v.Schedule && !v.Suspend)
                .GroupJoin(_context.ServiceIntervals(new DateTime(), new DateTime()),
                    v => v.Id,
                    si => si.VehicleId,
                    (v, si) => SetServiceIntervals(v, si));
        }

        private static Vehicle SetServiceIntervals(Vehicle v, IEnumerable<ServiceInterval> si)
        {
            v.RepairsToSchedule = si;
            return v;
        }

        #region EF Context
        public class FakeDatabaseContext : DbContext
        {
            public DbSet<Vehicle> Vehicles { get; set; }
            private DbSet<ServiceInterval> _serviceIntervals { get; set; }

            public IQueryable<ServiceInterval> ServiceIntervals(DateTime startingDate, DateTime endingDate)
            {
                return _serviceIntervals.FromSql($@"
                    SELECT *
                    FROM Stackoverflow2.dbo.ServiceIntervals"
                );
            }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(
                    @"Server=(localdb)\mssqllocaldb;Database=Stackoverflow;Integrated Security=True");
                optionsBuilder
                    .ConfigureWarnings(w => w.Throw(RelationalEventId.QueryClientEvaluationWarning));
            }
        }

        // Used to load a seperate database
        public class FakeDatabaseContext2 : DbContext
        {
            public DbSet<ServiceInterval> ServiceIntervals { get; set; }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(
                    @"Server=(localdb)\mssqllocaldb;Database=Stackoverflow2;Integrated Security=True");
                optionsBuilder
                    .ConfigureWarnings(w => w.Throw(RelationalEventId.QueryClientEvaluationWarning));
            }
        }

        public class Vehicle
        {
            public string Id { get; set; }
            public bool Schedule { get; set; }
            public bool Suspend { get; set; }
            public IEnumerable<ServiceInterval> RepairsToSchedule { get; set; }
        }

        public class ServiceInterval
        {
            public string Id { get; set; }
            public string VehicleId { get; set; }
        }
        #endregion EF Context

        #region Seed methods
        private static Random _random = new Random();
        private static bool _randomBool => _random.Next() % 2 == 1;

        private static void LoadContext()
        {
            var maxVehicles = 10;
            for (int i = 1; i < maxVehicles; i++)
            {
                _context.Vehicles.Add(new Vehicle { Id = i.ToString(), Schedule = _randomBool, Suspend = _randomBool });

                for (int o = 1; o < _random.Next(10); o++)
                {
                    _context2.ServiceIntervals.Add(new ServiceInterval { Id = ((maxVehicles * i) + o).ToString(), VehicleId = i.ToString() });
                }
            };

            _context.SaveChanges();
            _context2.SaveChanges();
        }

        private static void CleanContext()
        {
            _context.Vehicles.RemoveRange(_context.Vehicles.ToArray());
            _context2.ServiceIntervals.RemoveRange(_context2.ServiceIntervals.ToArray());
            _context.SaveChanges();
            _context2.SaveChanges();
        }
        #endregion Seed methods
    }
}

IntelliTrace显示此查询已执行:

SELECT [v].[Id], [v].[Schedule], [v].[Suspend], [si].[Id], [si].[VehicleId]
FROM [Vehicles] AS [v]
LEFT JOIN (

                        SELECT *
                        FROM Stackoverflow2.dbo.ServiceIntervals
) AS [si] ON [v].[Id] = [si].[VehicleId]
WHERE ([v].[Schedule] = 1) AND ([v].[Suspend] = 0)
ORDER BY [v].[Id]

我对此进行了几次测试,一切似乎都正常。

〜干杯

设置项目注释:

  1. 这是一个.NET Core 2.1控制台应用程序
  2. 安装软件包Microsoft.EntityFrameworkCore-2.2.6版
  3. 安装软件包Microsoft.EntityFrameworkCore.Design-版本2.2.6
  4. 安装软件包Microsoft.EntityFrameworkCore.SqlServer-版本2.2.6
  5. 安装软件包Microsoft.EntityFrameworkCore.SqlServer.Design-版本1.1.6
  6. 打开cmd窗口并导航到项目文件夹
  7. 在控制台中运行:dotnet ef迁移添加InitialCreate
  8. 在控制台中运行:dotnet ef数据库更新