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

时间:2011-05-19 11:19:10

标签: c# asp.net sql linq class

我不确定这是否是正确的做事方式,看起来很长,我想检查这是将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结果创建类实例的最佳方法吗?它变得非常长,有许多属性。

1 个答案:

答案 0 :(得分:6)

如果是一个小手册,你的方法是完全有效的。我曾参与过许多项目,这些项目使用这种方法从数据库查询中创建C#对象。但是,有一些技术可用于从查询中生成类型:

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