c# 将 linq 数据库记录转换为类实例
我不确定这是否是正确的处理方法,看起来很冗长,我想检查这是否是将 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 结果创建类实例的最佳方法吗?它变得非常冗长,有很多属性。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的方法是完全有效的,虽然有点手动。我参与过许多使用这种方法从数据库查询创建 C# 对象的项目。然而,有一些技术可用于从查询生成类型:
以上所有内容都可用于根据数据库模式生成类型。
Your approach is totally valid, if a little manual. I have worked on numerous projects that use this approach for creating C# objects from database queries. There are however a few technologies that can be used to generate types from queries:
All of the above can be used to generate types based on database schema.