Converting Anonymous Type To Nominal Type
I have a method here that should return a Rpt_IncidentWithConfirm object but I have no clue how to easily convert it to one. The only way I know how it do do what I have below which is very inefficient.
public Rpt_IncidentWithConfirm GetIncident(string IncidentID)
{
db = new IncidentsDataContext();
var incident = (from i in db.Rpt_IncidentWithConfirms
join d in db.DropDowns on i.incidentType equals d.value
where i.incidentID == Convert.ToInt32(IncidentID)
select new
{
i, d.text
}).SingleOrDefault();
Rpt_IncidentWithConfirm r = new Rpt_IncidentWithConfirm();
// I didn't want to have to type all this here because I have too开发者_C百科 many fields to map.
r.bhaIncident = incident.i.bhaIncident;
r.bitType = incident.i.bitType;
r.Bottom_Connection = incident.i.Bottom_Connection;
// And so on.
return r;
}
You can instantiate the Rpt_IncidentWithConfirm
object directly in the query expression and only refer to the database values you need:
var incident = (from i in db.Rpt_IncidentWithConfirms
join d in db.DropDowns on i.incidentType equals d.value
where i.incidentID == Convert.ToInt32(IncidentID)
select new Rpt_IncidentWithConfirm
{
bhaIncident = i.bhaIncident
, bitType = i.bitType
, Bottom_Connection = i.Bottom_Connection
}).SingleOrDefault();
Don't use anonymus type
you can use the type you have to return
select new Rpt_IncidentWithConfirm
{
// set all properties you need
}).SingleOrDefault();
Edit: If your query is on collection type you want to return you can simply use result of query:
return db.Rpt_IncidentWithConfirms.Where( ... ).FirstOrDefault();
or if u need value of text use :
//do something with incident.Text
return incident.i;
I actually used the answer linked below to solve my problem. It isn't exactly what I wanted to do but I don't have to type everything manually now. Return anonymous type results?
public class IncidentWithDropDown
{
public Rpt_IncidentWithConfirm Incident { get; set; }
public string IncidentTypeText { get; set; }
}
public IncidentWithDropDown GetIncident(string IncidentID)
{
db = new IncidentsDataContext();
var incident = (from i in db.Rpt_IncidentWithConfirms
join d in db.DropDowns on i.incidentType equals d.value
where i.incidentID == Convert.ToInt32(IncidentID)
select new IncidentWithDropDown()
{
Incident = i,
IncidentTypeText = d.text
}).SingleOrDefault();
return incident;
}
you are not required to create an anonymous type in the select just create an object of the the named type instead
public Rpt_IncidentWithConfirm GetIncident(string IncidentID)
{
db = new IncidentsDataContext();
var return (from i in db.Rpt_IncidentWithConfirms
join d in db.DropDowns on i.incidentType equals d.value
where i.incidentID == Convert.ToInt32(IncidentID)
select new Rpt_IncidentWithConfirm(){
bhaIncident =i.bhaIncident,
bitType = i.bitType,
Bottom_Connection = i.Bottom_Connection,
// And so on.
}).SingleOrDefault()
}
精彩评论