我这里有一个方法,它应该返回一个Rpt_IncidentWithConfirm对象,但我不知道如何轻松地将其转换为一个对象。我所知道的唯一方法是如何做下面的事情,这是非常低效的。
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 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;
}发布于 2011-09-09 21:21:50
我实际上使用了下面链接的答案来解决我的问题。这并不完全是我想要做的,但我现在不必手动键入所有内容。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;
}发布于 2011-09-09 04:50:36
您可以在查询表达式中直接实例化Rpt_IncidentWithConfirm对象,并且只引用所需的数据库值:
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();发布于 2011-09-09 04:51:59
不要使用anonymus type,可以使用必须返回的类型
select new Rpt_IncidentWithConfirm
{
// set all properties you need
}).SingleOrDefault();编辑:如果你的查询是关于你想要返回的集合类型,你可以简单地使用查询的结果:
return db.Rpt_IncidentWithConfirms.Where( ... ).FirstOrDefault();或者如果您需要文本的值,请使用:
//do something with incident.Text
return incident.i;https://stackoverflow.com/questions/7354288
复制相似问题