gpt4 book ai didi

c# 将 linq 数据库记录转换为类实例

转载 作者:行者123 更新时间:2023-12-03 21:38:18 25 4
gpt4 key购买 nike

我不确定这是否是正确的处理方法,看起来很冗长,我想检查一下这是否是将 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# 对象的项目。然而,有一些技术可用于从查询生成类型:

以上所有内容都可用于根据数据库架构生成类型。

关于c# 将 linq 数据库记录转换为类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6057817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com