tags:

views:

65

answers:

2

I'd like to use Linq to SQL in my windows form application.

The data in the local database is fetched from the Web Service or created locally.

If an entity was fetched from the Web Service it has ExternalId set up

I frequently need to use code as below to fetch objects by theirs ExternalId:

var user = (from u in db.User
            where u.ExternalId == userExternalId
            select u).First();

var location = (from l in db.Location
            where l.ExternalId == locationExternalId
            select l).First();

So I've though about changing it to a generic function as the one below:

internal TEntity FetchByExternalId<TEntity>(System.Data.Linq.Table<TEntity> table,
                                               int externalId) 
where TEntity: IExternalStorable
{
    return (from obj in table
            where obj.ExternalId == externalId
            select (TEntity)obj).First();
}

Unfortunately such function doesn't compile:

  1. I can't add IExternalStorable to entity class as the code is generated from the database (I've though about using partial classes but it doesn't seems to work)
  2. It C# complains that TEntity isn't reference type I'm not sure how the generic "where" constrain should look like.

Any ideas how to use linq in generic functions?

+1  A: 

1: partial classes really should work. have you checked that the namespaces are the same? what error are you getting?

2: should be

where TEntity : class, IExternalStorable

since otherwise it could be, say, another interface, which couldn't be instantiated

David Hedlund
Re: 1. It was problem with the namespace :) Thanks.
Piotr Czapla
Problem solved. Thank you!
Piotr Czapla
+2  A: 

Consider leveraging the framework instead of rolling your own:

Location location = db.Locations
  .First(loc => loc.ExternalId == locationExternalId);
David B
Thank you :) I will update my code
Piotr Czapla