Reputation: 26532
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:
Any ideas how to use linq in generic functions?
Upvotes: 0
Views: 98
Reputation: 110111
Consider leveraging the framework instead of rolling your own:
Location location = db.Locations
.First(loc => loc.ExternalId == locationExternalId);
Upvotes: 2
Reputation: 129792
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
Upvotes: 1