c# Turning a linq database record into a class instance


I'm not sure if this is the correct way to do things, it seems quite long winded and I want to check that this is a good way of turning a linq result into a class:

 /// <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)
    public JobHeader(tblJobHeader 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;

Firstly I'm aware that the data source is not well formed (please ignore incorrect types etc etc), there's not much I can do about that at the moment. My query in specifically in regards to is this the best way to create an instance of a class from a Linq result? It becomes very long winded with a lot of properties.

Tom GullenH
2011-05-19 11:19:10 Scores:2

1 answer

Answer 1

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.

ColinE H
2011-05-19 11:25:06
Share |
View original post at stackoverflow.com

Related topics

Duplicate a database record with linq

Is there a way to duplicate a db record with linq to sql in c#? Id [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [Foo] [nvarchar](255) NOT NULL, [Bar] [numeric](28,12) NOT NULL, ... Given the table above, I would like to duplicate a record (but give it a different id), in a way that new fields added ...

Instance of Linq class without connecting it to database

Is there a way to create an instance of a linq class without it being included in the next Submit? like this: Customer customer = new Customer(); Context.SubmitChanges(); // customer is not added. I get an error back saying that some values can not be null because constraints in the database, even ...

c# linq: how to submit object to database as a new record

I have the following object: namespace LearnLINQ1 { [Table(Name="testMe")] public class SubmitTest { [Column(Name="FirstName")] public string FirstName { get; set; } [Column(Name ...

Retrieve Random Record/Row from DataBase Table Using LINQ 2 SQL

I have in DB table Called Students We make some thing like lottery to know which students are going to be the winner in some thing like game in a school public static List<Students> GetAll() { List<Students> list = new List<Students>(); var query = ...

how to get the last record number after inserting record to database in access

i have database in access with auto increase field (ID). i insert record like this (in C#) SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') "; OleDbCommand Cmd = new OleDbCommand(SQL, Conn); Cmd.ExecuteNonQuery(); Cmd.Dispose(); Conn.Close(); how to get the last inserting number ? i dont want to run new query ...

updating a database record with linq to sql in c#

I have a function that looks like this: public UpdateRecord(MyObjectModel TheObject, int TheUserID) { using (MyDataContextModel TheDC = new MyDataContextModel()) { var TheObjectInDB = (from o in TheDC.TheObjects ...

How would I use Linq-To-Nhibernate (NH3.2) to have the database return to me the record count of a query without the records themselves?

I have a bunch of queries to run, and if any of them return even a single result, I toggle a boolean variable true. If they all return no results, then it stays false. Right now I'm just picking the smallest column and .Select() ing it, and then counting the results ...

How to achieve mutual exclusion on a database record in linq sql

I have a distributed client server system which has multiple 'worker' engines and a WCF service, lets call it, FileManagerService, which adds 'jobs' to a database for the 'worker' engines to pick up and process. The database consists of two tables: Jobs and File. Every job operates on a File ( ...

Update record in TableServiceContext by a new instance of the record object?

I've got an azure table record object defined as [DataServiceKey("PartitionKey", "RowKey")] public class TableRecord { public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTime Timestamp { get; set; } public string Data { ...

Using LINQ and a dropdownlist to enter a new record into an SQL Database

Hi Everyone I'm a new and I'm struggling with my asp.net website, Our remit is to make a Veterinary Surgery Booking System. I have an asp.net page that has 4 fields, one of the fields is populated on page load as per the vb code below. I'm trying to get the selected ...