如何仅使用LINQ to Entities包含内部列表的一些项目

时间:2016-03-28 16:45:30

标签: c# entity-framework linq

我有以下实体(为便于阅读而简化):

public class Country
{
    public List<NameLocalized> Names;
}

public class NameLocalized
{
    public string Locale;
    public string Value;
}

我的上下文中也有DbSet<Country> Countries。如何编写LINQ查询,它将返回国家/地区列表但具有已过滤的名称(因此Names列表将仅包含基于指定区域设置的单个项目。这样的事情(但是,这不是一个有效的例子)

public List<Country> GetCountries(string locale)
{
    var result = context.Countries.Include(c => c.Names.Select(n => n.Locale == locale)).ToList();
    return result;
}

如果在一个

中无法实现,如何分两步完成
public List<Country> GetCountries(string locale)
{
    //I have to use Include for eager loading
    var tempResult = context.Countries.Include(c => c.Names);

    var result = //Some code to convert tempResult to result, where only interesting locale is included
    return result;
}

我正在尝试使用代码删除不必要的项目,但它也不起作用

result.ForEach(c => c.Names.ToList().RemoveAll(n => n.Locale != locale)); 

更新: 我已设法删除包含以下代码的项目(使用扩展方法)

public static void RemoveAll<T>(this ICollection<T> collection,Predicate<T> predicate) 
{
    if (predicate == null)
    {
        throw new ArgumentNullException("predicate");
    }
     collection.Where(entity => predicate(entity))
        .ToList().ForEach(entity => collection.Remove(entity));
}


result.ForEach(c => c.Names.RemoveAll(n => n.Locale != locale));

UPDATE2:

在答案和评论的帮助下,我获得了成功。详细信息位于Convert Entity with navigation property to DTO using IQueryable

2 个答案:

答案 0 :(得分:1)

由于您的模型将Country定义为具有多个Names的内容,因此让Country实例只有一个Names可能会造成混淆。相反,请创建一个单独的类型来表示已知给定区域设置Country的信息的概念。

public class LocaleCountry
{
    public int CountryId {get;set;}
    public string Name {get;set;}
    public string Locale {get;set;}
}


public List<LocaleCountry> GetCountries(string locale)
{
    var result = context.Countries
        .Select(c => new LocaleCountry
        {
            CountryId = c.Id,
            Name = c.Names
               .Where(n => n.Locale == locale)
               .Select(n => n.Name)),
            Locale = locale
        })
        .ToList();
    return result;
}

答案 1 :(得分:0)

public List<Country> GetCountries(string locale)
{
    var result = context.Countries.Select(c => new Country { Names = c.Names.Select(n => n.Locale == locale).ToList() }).ToList();
    return result;
}

public List<Country> GetCountries(string locale)
{
    var result = context.Countries.Where(c => c.Names.Any(n => n.Locale == locale)).ToList();
    result.ForEach(c => c.Names = c.Names.Where(n => n.Locale == locale).ToList());
    return result;
}