Piotr Czapla
Piotr Czapla

Reputation: 26532

Extracting generic Linq queries

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?

Upvotes: 0

Views: 98

Answers (2)

Amy B
Amy B

Reputation: 110111

Consider leveraging the framework instead of rolling your own:

Location location = db.Locations
  .First(loc => loc.ExternalId == locationExternalId);

Upvotes: 2

David Hedlund
David Hedlund

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

Related Questions