使用字符串展开已编写的 c# linq 查询(无方法)

本文关键字:查询 linq 方法 字符串 | 更新日期: 2023-09-27 18:33:53

我有这样的代码。

上下文:

public class TestContext : System.Data.Entity.DbContext
{
    public TestContext()
        : base("name=TestContext")
    {
    }
    public System.Data.Entity.DbSet<TestClass> TestClass { get; set; }
    public System.Data.Entity.DbSet<TestSubClass> TestSubClass { get; set; }
}

测试类:

public class TestClass
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }
}

测试子类:

public class TestSubClass
{
    [Key]
    public Guid Id { get; set; }
    public int Status { get; set; }
    [Column("Test")]
    public Guid? TestId { get; set; }
    [ForeignKey("TestId")]
    public virtual TestClass Test { get; set; }
}

获取一切:/问题

public static IQueryable<TestClass> GetEverything(bool onlyVisible = false)
{
    IQueryable<TestClass> query;
    using(var context = new TestContext())
    {
        query = from test in context.TestClass
                select test;
        if (onlyVisible)
        {
            query
                .Join(context.TestSubClass, test => test.Id, testSub => testSub.TestId, (test, testSub) => new { TestClass = test, TestSubClass = testSub })
                .Where(test => test.TestSubClass.Status == 1)
            ;
            /*
             * I want to add something like this:
             * 
               query += 
                   join testSub in context.TestSubClass on test.Id equals testSub.TestId
                   where testSub.Status == 1
               ;
             */
        }
    }
    return query;
}

如果你看评论,你知道我想要什么。

问题是我不知道如何将这些东西的多个性能结合起来。

或者我怎样才能更好地结合它?

我有一个基本query string,可以通过其他东西来扩展。但我认为这些额外的东西对于第三人来说不是很好读和不稳定......

使用字符串展开已编写的 c# linq 查询(无方法)

我认为您可以尝试使用以下方法:

public class TestClass
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<TestSubClass> TestSubs {get;set;}
}
public class TestSubClass
{
    [Key]
    public Guid Id { get; set; }
    public int Status { get; set; }
    [Column("Test")]
    public Guid? TestId { get; set; }
    [ForeignKey("TestId")]
    public virtual TestClass Test { get; set; }
}
public static IQueryable<TestClass> GetEverything(bool onlyVisible = false)
{
      var context = new TestContext();
      var query = from test in context.TestClass
                select test;
      if (onlyVisible)
      {
           query = query.Include(i => i.TestSubs).Where(w => w.TestSubs.Any(a => a.Status == 1));
      }
      return query;
}

Include指示 EF 急切加载实体。查看有关加载相关实体的 EF 策略的文章