user1555686
user1555686

Reputation: 13

Wrong selection from database using Entity Framework

I have a method that selects two fields from database where text in first field match some value

public static List<List<string>> SelectForSearch(string letter)
{
    var data = (from p in model.City
                where p.Name.StartsWith(letter)
                select new List<string> { p.Name, p.CountryName }).ToList();
    return data;
}

But it returns me a list like this:

[0][0]Australia
[0][1]Ballina

[1][0]Berry
[1][1]Australia

[2][0]Australia
[2][1]Bendigo
...

Country and City possition don't have a static index like this:

[0][0]Ballina
[0][1]Australia

[1][0]Berry
[1][1]Australia

[2][0]Bendigo
[2][1]Australia
...

Upvotes: 1

Views: 85

Answers (1)

Manatherin
Manatherin

Reputation: 4187

Your issue is that in your select statement, instead of creating a type with Name and CountryName you are creating a List of strings. The List initialiser allows you to pass in the values when the list is constructed by placing them in { } and you are using this ability by accident, as you saw it creates a list of strings where the name is the first element and the country name is the second element. What you want to be doing is more like:

var data = (from p in model.City
            where p.Name.StartsWith(letter)
            select new { City = p.Name, CountryName = p.CountryName }).ToList();
return data;

This is using anonymous types which is not good as you want to declare a type for the return value. So you should really create a class for storage, for example:

public class CityCountryPair 
{
    public String City { get; set; }
    public String CountryName { get; set; }
}

then your method becomes

public static List<CityCountryPair> SelectForSearch(string letter)
{
    var data = (from p in model.City
                where p.Name.StartsWith(letter)
                select new CityCountryPair() { City = p.Name, 
                                               CountryName = p.CountryName 
                                              }).ToList();
    return data;
}

Upvotes: 2

Related Questions