RockStar
RockStar

Reputation: 87

Entity framework query not working using asp.net

My entity framework query is not returning any value. I wanted to replicate this query through entity framework: SELECT name FROM guitarBrands WHERE image = image. So I ended up trying this code below.

public static string GetBrandByImage(string imageType)
{
    BrandsDBEntities obj = new BrandsDBEntities();

    string name = (from g in obj.guitarBrands where g.image == imageType select g.name).ToString();

    return name;
}

I'm really new at using entity framework and i really hope you guys can provide solutions for this.

Upvotes: 1

Views: 573

Answers (2)

Xilmiki
Xilmiki

Reputation: 1502

(from g in obj.guitarBrands where g.image == imageType select g.name)

return a list like an SQL query

To get the first element

(from g in obj.guitarBrands where g.image == imageType select g.name).First().Tostring();

or equivalent

obj.guitarBrands.Where(g => g.image == imageType).First().name;

Upvotes: 2

Nkosi
Nkosi

Reputation: 247098

You are calling ToString on the query itself. Query needs to be enumerated first

public static string GetBrandByImage(string imageType) {
    using(var obj = new BrandsDBEntities()) {    
        var name = (from g in obj.guitarBrands 
                    where g.image == imageType 
                    select g.name).FirstOrDefault();

        return name;
    }
}

Using FirstOrDefault on the query as is would return the first name from any guitar brand that matches the predicate or null if no matches are found.

Upvotes: 1

Related Questions