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:
- 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)
- 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?