Pregunta

Vs'12, asp.net MVC4 Internet Application, EF Code First, MySQL db

Overview

I am trying to create a report with EPPlus from a Controller level. - User clicks button program gets here, i need to query the database for some information..

Explanation

I tried this way: Where intPR=1 as a passed in variable

var pro = from p in db.Prospect
        where p.ProspectID == intPR
        select p;
var cty = from c in db.Countys
        from p in db.Prospect
        where p.ProspectID == intPR
        select c;

then I would use something like this to set it to the field

string x = pro.Select(p => p.ProspectName).ToString();
          ws.Cells["E" + LineFeed].Value = x;

string xx = cty.Select(m => m.County).ToString();
          ws.Cells["E" + LineFeed].Value = xx;

All i get is the super long query string

"SELECT 
[Extent1]...... You get the hint

Question

Why am i not getting values?

¿Fue útil?

Solución

Since you're using LINQ, the expression only gets evaluated when the results are really needed. Note that select actually returns an IEnumerable or IQueryable. It's only if actually want to use the values that it executes the query. The default ToString() method just prints the query.

You could for example call the ToList() method to make sure the query is exectuted:

var prospects = pro.Select(p => p.ProspectName).ToList();

However, this will return a list of prospects, calling the ToString()-method on that would still yield just the name of the type. If you want the first item of the list you can do the following:

var firstProspectName = pro.Select(p => p.ProspectName).First():

EDIT: Your query could be written a bit more concise, without intermediate steps:

var firstProspectName = db.Prospect.where(p => p.ProspectID == intPR)
                                   .Select(p => p.ProspectName)
                                   .First();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top