C# – How to retrieve data with LINQ to SQL into a weakly-typed object that can be moved around

ado.netclinqlinq-to-sql

In classic ASP we had the record set object. With ADO.Net we had the datatable.

Both were simple .Net objects that could be moved around easily.

What is the equivalent for using LINQ To SQL?

Most examples show "var" being used, however, this seems completely non-oo as you can't move a var around (without a cast hack). My understanding is that, in "proper" OO, you would never retrieve data and use it in the same place, so I can't see any value in using var with LINQ to SQL.

I understand that I can make a custom object for every single dataset I retrieve. However, I don't really want to do this as it seems like extra work and complexity. If I looped any of this data 1000 times w boxing/unboxing, I would do that. But in this case, I'm not looping and want to keep things simple, I'm not afraid to have a little boxing/unboxing, I can't imagine it affecting performance in a noticeable way.

Here is the code I'm working with:

using (ormDataContext context = new ormDataContext(connStr))
{
    var electionInfo = from t1 in context.elections
               join t2 in context.election_status
               on t1.statusID equals t2.statusID
               select new { t1, t2 };
}

Best Answer

You should qualify what you mean by "move around". Much of what you might have done in Classic ASP is now considered to be a bad practice, be careful not to repeat well known mistakes which have had solutions for some years now.

Also, "var" is strongly-typed, just anonymous: "no name", not "no type".

Please say what you mean about "proper OO" not permitting data to be both fetched and used in the same place.

Also, remember that examples are meant to show off individual features. No single example is going to show you everything. In particular, the answer to "how do I return an anonymous type" is "you don't return anonymous types". For instance:

using (ormDataContext context = new ormDataContext(connStr))
{
    var electionInfo = from t1 in context.elections
               join t2 in context.election_status
               on t1.statusID equals t2.statusID
               select new ElectionWithStatus { Election=t1, Status=t2 };
}

Where:

public class ElectionWithStatus {
    public Election Election {get;set;}
    public ElectionStatus Status {get;set;}
}

So, bottom line, if you have to move it around, then move a strongly-typed object, not a weakly-typed object.

Related Topic