Here is the method:
public IEnumerable<???> GetAllSiteVisits()
{
var visits =
_db.STEWARDSHIP
.OrderByDescending(r => r.VISIT_DATE)
.Select(r => new
{
id = r.STEWARDSHIP_ID,
name = r.SITE.SITE_NAME,
visit_date = r.VISIT_DATE,
visit_type = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC
});
return visits;
}
I am using the Entity Framework 4.2.
So the problem is figuring out the return type. If I were just to use the info directly from the DB table, I'd return IEnumerable<STEWARDSHIP> but since I am selecting only certain fields, I don't understand what the return type is.
Return type will be a collection of AnonymousType where each item represents a class with the following properties:
id (with type of the r.STEWARDSHIP_ID)name (with type of the r.SITE.SITE_NAME)visit_date (with type of the r.VISIT_DATE)visit_type (with type of the r.VISIT_TYPE_VAL.VISIT_TYPE_DESC)Then you can loop through the elements using foreach loop:
foreach(var item in visits)
{
string visitInfo = String.Format(
CultureInfo.InvariantCulture,
"Id: {0}, Name: {1}, Date: {2}, Type: {3}",
item.id,
item.name,
item.visit_date,
item = visit_type);
Debug.WriteLine(visitInfo);
}
If you need to return results of the query from the method you can introduce a new class which represent these fore properties:
// TODO: update types of the properties
class VisitDetails
{
public string Id { get; private set; }
public string Name { get; private set; }
public DateTime VisitDate { get; private set; }
public string VisitType { get; private set; }
}
And update query to create instances of VisitDetails rather than Anonymous Type:
.Select(r => new VisitDetails
{
Id = r.STEWARDSHIP_ID,
Name = r.SITE.SITE_NAME,
VisitDate = r.VISIT_DATE,
VisitType = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC
});
In this way return type would be IEnumerable<VisitDetails> so you easily can even return results of the query itself from the method by specifying exact return type as well so code would be much clean.
See Object Initializers with anonymous types for more details.
You won't be able to, it's returning an Anonymous type. Read the MSDN documentation on this topic.
One alternative would be to create a concrete implementation using a class that has
as properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With