我不确定这是否是正确的做事方法,这似乎很冗长,我想检查这是将 linq 结果转换为类的好方法:
/// <summary>
/// A job header
/// </summary>
public class JobHeader
{
public int ID { get; set; }
public int? UserID { get; set; }
public int? ClientID { get; set; }
public string JobName { get; set; }
public string Code { get; set; }
public DateTime? DateAdded { get; set; }
public int? StatusID { get; set; }
public bool UniversalQuantity { get; set; }
public bool UniversalDelivery { get; set; }
public bool UniversalDeliveryDates { get; set; }
public bool BuyerHidden { get; set; }
public bool FullfillmentDone { get; set; }
public string TNTCode { get; set; }
public int? ContactUserID { get; set; }
public string ContactDepartment { get; set; }
public string ConactName { get; set; }
public DateTime? DateSubmitted { get; set; }
public bool CampaignJob { get; set; }
public bool UniversalBusinessUnits { get; set; }
public bool TenderJob { get; set; }
public Jobs.JobLine[] JobLines { get; set; }
/// <summary>
/// Create instance on db record ID
/// </summary>
public JobHeader(int? RecordID)
{
if (RecordID != null)
{
using (MainContext db = new MainContext())
{
var q = (from h in db.tblJobHeaders where h.id == RecordID select h).SingleOrDefault();
if (q != null)
LoadByRec(q);
}
}
}
public JobHeader(tblJobHeader Rec)
{
LoadByRec(Rec);
}
/// <summary>
/// Sets properties to match database record
/// </summary>
private void LoadByRec(tblJobHeader Rec)
{
this.ID = Rec.id;
this.UserID = Rec.userID;
this.ClientID = Rec.ClientID;
this.JobName = Rec.JobName;
this.Code = Rec.JobCode;
this.DateAdded = Rec.dateAdded;
this.StatusID = Rec.statusID;
this.UniversalQuantity = Rec.uniQty == 1;
this.UniversalDelivery = Rec.uniDelivery == 1;
this.UniversalDeliveryDates = Rec.uniDeliveryDates == 1;
this.BuyerHidden = Rec.buyerHidden == 1;
this.FullfillmentDone = Rec.fulfilmentDone == 1;
this.TNTCode = Rec.jobTntCode;
this.ContactUserID = Rec.JobClientContactID;
this.ContactDepartment = Rec.JobClient;
this.ConactName = Rec.JobAccountHandler;
this.DateSubmitted = Rec.dateSubmitted;
this.CampaignJob = Rec.isCampaignJob == 1;
this.UniversalBusinessUnits = Rec.uniBusUnits == 1;
this.TenderJob = Rec.isTenderJob == 1;
}
}
首先,我知道数据源的格式不正确(请忽略不正确的类型等),目前我对此无能为力。 我的查询是关于这是从 Linq 结果创建类实例的最佳方法吗? 它变得非常冗长,有很多属性。
你的方法是完全有效的,如果有点手动的话。我参与过许多使用此方法从数据库查询创建 C# 对象的项目。但是,有一些技术可用于从查询生成类型:
- 类型化数据集 - 一种略显过时的方法
- Linq to SQL
- 实体框架
以上所有内容都可用于基于数据库架构生成类型。