Brian Mains
Brian Mains

Reputation: 50728

LINQ-to-SQL equivalent to ADO.NET EF's GetObjectByKey

I wrote some plumbing for getting an object by its identifer. Behind the scenes, it uses GetObjectByKey or TryGetObjectByKey to get an object by its EntityKey, which can be constructed. Does LINQ to SQL have something equivalent to this?

Thanks.

Upvotes: 0

Views: 419

Answers (1)

devuxer
devuxer

Reputation: 42374

Here's what I've been using:

public virtual TEntity GetById(int id)
{
    var table = DataContext.GetTable<TEntity>();
    var mapping = DataContext.Mapping.GetTable(typeof(TEntity));
    var idProperty = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
    var param = Expression.Parameter(typeof(TEntity), "e");
    var predicate = Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(
        Expression.Property(param, idProperty.Name), Expression.Constant(id)), param);
    return table.SingleOrDefault(predicate);
}

I'm using this method inside a generic Repository class that looks like this:

public class Repository<TDataContext, TEntity> : IDisposable
    where TDataContext : DataContext
    where TEntity : class
{
    protected TDataContext DataContext { get; private set; }

    public Repository(TDataContext dataContext)
    {
        DataContext = dataContext;
    }

    ...
}

Upvotes: 2

Related Questions