使用字符串扩展写入的c#linq查询(无方法)

时间:2014-12-10 13:03:29

标签: c# performance linq

我有这样的代码。

上下文

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

识别TestClass:

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

TestSubClass:

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

GetEverything:/ Problem

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,可以通过其他内容进行扩展。 但是我觉得这些额外的东西对于第三人来说并不是很容易理解和明白......

1 个答案:

答案 0 :(得分:1)

我认为您可以尝试使用以下内容:

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 strategies for loading related entities

上的文章