简体   繁体   中英

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.

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;
    }

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM