1

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.

1
  • A few things: Please provide more info, especially what exactly is returned from your query. Is it null? Is it an empty string? Secondly, have you tried the same query with LINQ? (string name = (obj.Set<guitarBrands>().Where(g => g.image == imageType).Select( g => g.name).ToString();Thirdly, you should always use using with contexts: using( var obj = new BrandsDBEntities() ) { ... }. Finally, what version of EF are you using? Commented Jun 17, 2017 at 11:43

2 Answers 2

2
(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;
Sign up to request clarification or add additional context in comments.

1 Comment

Do mention that if there are no matches and First is called you would get an exception.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.