3

I have following entities (simplified for readability):

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

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

I also have a DbSet<Country> Countries in my context. How to write a LINQ query which will return the list of countries but with filtered Names (so Names list will contain only single item based on specified locale. Something like this (however, this is not a working example)

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

How to achieve this in 2 steps if not possible in one

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

I am trying following code to remove unnecessary items, but it does not work too

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

UPDATE: I have managed to remove items with following code (using extension method)

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:

With the help of answers and comments I was able to succeed. Details are at Convert Entity with navigation property to DTO using IQueryable

4
  • It's all (Include) or nothing. No third option.
    – Ivan Stoev
    Mar 28, 2016 at 17:00
  • See this useful library. Mar 28, 2016 at 19:22
  • Be aware that if you remove entities and then save the context then you'll end up removing those relationships in your database. I would seriously warn against the approach you've come up with, as it's likely to cause you pain in the future. Mar 30, 2016 at 15:49
  • @StriplingWarrior I have to agree
    – Ingweland
    Mar 30, 2016 at 16:28

2 Answers 2

1

Since your model defines Country as something that has multiple Names, it may be confusing to have a Country instance that only has one of its Names. Instead, create a separate type to represent the concept of the information that is known about a Country for a given locale.

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;
}
9
  • Actually, that's what I doing after I query database. (did not include this part for brevity). I am just not quite happy manually creating new objects (my DTO is automatically generated by some VS extension)
    – Ingweland
    Mar 28, 2016 at 20:35
  • @Ingweland: Well, as far as I can tell, this is still the best approach. It allows Entity Framework to only get out exactly the information that it needs from the database in a single round-trip. Can you explain why you don't want to "create new objects?" If there's a legitimate reason not to map to the generated DTO, then create a separate one. Mar 30, 2016 at 15:48
  • The main reason why I want to avoid manual creation is that it's easy to forget to update such places later in case entity's structure is changed. Plus, in my real project, the entity is quite complex. Maybe it's better to create some proxy object, which will hold Country (but without Names at all) and concrete Name as separate property. Then, to feed EntityToDto converter with this proxy object. What do you think?
    – Ingweland
    Mar 30, 2016 at 16:34
  • @Ingweland: You've identified a class that you want to be solely responsible for converting Entities to DTOs, right? It would work okay to feed it the countries and names separately, but it may be simpler to either make that class provide an Expression<Func<Country, CountryNameDto>> which other classes could throw into a .Select() off of a list of countries, or make that class's function apply its transformation to a given IQueryable<Country> parameter, so you can still get the advantages of deferred execution while applying the Single Responsibility Principle. Mar 30, 2016 at 19:43
  • It would be awesome if you can provide some code example describing your suggestions. I am still learning c# and not sure how to implement them into workable solution.
    – Ingweland
    Mar 30, 2016 at 20:13
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;
}
8
  • Is this the only way? I have a lot of properties in my real Entity type, and I would like to avoid creating anonymous objects where I have to map all those properties.
    – Ingweland
    Mar 28, 2016 at 16:53
  • No, I will add another way Mar 28, 2016 at 16:53
  • the problem, is the second method load the entire table in memory
    – George
    Mar 28, 2016 at 16:56
  • the second method does not work - produces compile time error
    – Ingweland
    Mar 28, 2016 at 17:08
  • Cannot implicitly convert IEnumarable<bool> to ICollection<Country> - this is on the line with ForEach
    – Ingweland
    Mar 28, 2016 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.