我在这里有一个方法应该返回一个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;
}
答案 0 :(得分:3)
您可以直接在查询表达式中实例化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();
答案 1 :(得分:2)
不要使用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;
答案 2 :(得分:1)
我实际上使用下面链接的答案来解决我的问题。这不是我想要做的,但我现在不必手动输入所有内容。 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;
}
答案 3 :(得分:0)
您不需要在select中创建匿名类型而只需创建指定类型的对象
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()
}