开发者

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 constructe开发者_运维百科d. 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;
    }

    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜