代码之家  ›  专栏  ›  技术社区  ›  Brian Mains

linq to sql相当于ado.net ef的getObjectByKey

  •  0
  • Brian Mains  · 技术社区  · 14 年前

    我写了一些管道,用它的识别器找到一个物体。在后台,它使用getObjectByKey或TryGetObjectByKey来获取一个可以构造的EntityKey对象。Linq to SQL是否具有与此等效的内容?

    谢谢。

    1 回复  |  直到 14 年前
        1
  •  2
  •   devuxer    14 年前

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

    Repository

    public class Repository<TDataContext, TEntity> : IDisposable
        where TDataContext : DataContext
        where TEntity : class
    {
        protected TDataContext DataContext { get; private set; }
    
        public Repository(TDataContext dataContext)
        {
            DataContext = dataContext;
        }
    
        ...
    }