繁体   English   中英

具有动态Linq的实体框架

[英]Entity Framework with Dynamic Linq

使用EntityFramework上下文,我需要搜索许多字段。

EntityDBContext包括

public class Brand
{
    public int BrandID { get; set; }
    public string BrandName { get; set; }
    public string BrandDesc { get; set; }
    public string BrandUrl { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public string Name {get;set;}
            public DateTime CreatedDate {get;set;}    
            public DateTime ExpiryDate {get;set;}
    //The product class also contains many fields.(not shown here)
}

var context = new EntityDBContext();

我想使用“产品”中的字段来搜索品牌。 产品的字段仅在运行时已知。 如何使用产品字段构建表达式以搜索品牌。 请看截图。 谢谢,Binod

用户搜索表

首先,我对您的问题的这一部分不清楚:

the fields of the product are only known at run time.
怎么会这样? 您能否详细说明一下,因为我没有看到使用EF的有效实现。 您的数据库表(可能是Products )设置了什么? 该类中有哪些属性?

我们需要知道这一点,然后才能为您提供准确的答案 但是,我将给您一个更一般的示例,也许可以帮助您理解。

var all_brands_that_sell_shoes = /* But not always ONLY shoes */
        myDataContext.Brands
                     .Where(brand =>
                                 brand.Products.Any(product =>
                                                          product.Type == "Shoe")
                            )
                     .ToList();

编辑

如果我重新阅读了您的问题,您的意思是说直到运行时才知道Product类的属性; 但是您事先不知道需要应用哪些过滤器以及需要跳过哪些过滤器?

第二个答案假设这就是您想要的。 同样,由于您没有发布您的类的属性,因此我不知道它们的属性,因此出于示例的目的,我发明了自己的字段。

首先,制作如下所示的对象。 这将用于汇总您希望应用于选择的所有过滤器:

public class MySearchCriteria
{
    public string ProductName_Contains   { get; set; }
    public int    ProductWeight_LessThan { get; set; }
    public int    ProductType_Id         { get; set; }
}

当您要过滤列表时,可以将MySearchCriteria对象传递给该方法:

public List<Brand> GetFilteredList(MySearchCriteria filters)
{
    var brands = myDataContext.Brands; //All brands (for now)

    if(filters.ProductType_Id > 0)
    {
          //IF the filter has a value, filter the list accordingly:
          brands = brands.Where(brand => brand.Products.Any(product => product.TypeId == filters.ProductType_Id);
    }

    if(filters.ProductWeight_LessThan > 0)
    {
          //IF the filter has a value, filter the list accordingly:
          brands = brands.Where(brand => brand.Products.Any(product => product.Weight < filters.ProductWeight_LessThan));
    }

    if(!String.IsNullOrWhiteSpace(filters.ProductName_Contains))
    {
          //IF the filter has a value, filter the list accordingly:
          brands = brands.Where(brand => brand.Products.Any(product => product.Name.Contains(filters.ProductName_Contains)));
    }

     return brands.ToList();
}

此方法确保根据您提供的SearchCriteria过滤列表。

如果您不使用字段过滤器。例如, filters.ProductName_Contains它将是一个空字符串,并且if-evaluation会阻止您基于空字符串进行过滤。 最后,您将不会应用基于名称的过滤器。

我希望这是您想要的答案? 如果没有,请详细说明,因为我当时无法理解您想要的是什么。

暂无
暂无

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

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