tags:

views:

49

answers:

2

Given such table:

Foo
  P1
  P2
  P3

How can I read Foo with P1 only? My implementation:

public Foo GetFooWithP1(int id)
{
     using (DbDataContext db = new DbDataContext())
     {
        var query =
            from f in db.Foos
            where f.Id == id
            select new
            {
                P1 = m.P1
            };

        var data = query.SingleOrDefault();

        return new Foo
        {
            P1 = data.P1
        };
    }
}

Are there any alternatives?

+2  A: 

Note that for a single column you could get rid of the anon-type completely, and just select f.P1, but I'll leave that in as it scales to 2/3/etc columns...

How about:

    var query =
        (from f in db.Foos
        where f.Id == id
        select new { f.P1 }).AsEnumerable()
           .Select(row => new Foo { P1 = row.P1});

The main thing is to break the composition; AsEnumerable() does that for us.

I also wrote some code for DbLinq that allows this type of construct natively - it may work on LINQ-to-SQL; it is on usenet somewhere...

You could also use something like PropertyCopy() (MiscUtil) to avoid having to map it yourself:

var tmp = (from f in db.Foos
           where f.Id == id
           select new { f.P1 }).Single();
return PropertyCopy<Foo>.CopyFrom(tmp);
Marc Gravell
Thank you, Marc, for you hints! Now let me complicate things :-) http://stackoverflow.com/questions/959417/linqtosql-read-objects-hierarchy-with-only-certain-properties
alex2k8
A: 

One more solution:

db.ExecuteQuery<Foo>("SELECT Id, P1 FROM Foos WHERE Id = {0}", id).Single();
alex2k8