使用LINQ to SQL确定主键

Kei*_*ler 5 c# linq-to-sql

我正在编写一个基于LINQ to SQL的存储库,我想允许带有int参数的GetByID.签名是:

public T GetByID(int id)
{
     // Return
     return _dataContext.GetTable<T>() ....;
}
Run Code Online (Sandbox Code Playgroud)

我的表具有不同的主键名称.我想做的是为每个T动态确定主键是什么,并查询其值为integer = id.任何想法如何最好地解决这个问题?

Mar*_*ell 10

像下面的东西(支持其他类型int,但默认为int).重要的是,不要陷入Attribute通过反射查看数据的陷阱; LINQ-to-SQL也支持没有属性的对象:

public static TEntity Get<TEntity>(this DataContext dataContext, int id)
        where TEntity : class
{
    return Get<TEntity, int>(dataContext, id);
}
public static TEntity Get<TEntity, TKey>(this DataContext dataContext, TKey id)
    where TEntity : class
{
    // get the row from the database using the meta-model
    MetaType meta = dataContext.Mapping.GetTable(typeof(TEntity)).RowType;
    if (meta.IdentityMembers.Count != 1) throw new InvalidOperationException(
        "Composite identity not supported");
    string idName = meta.IdentityMembers[0].Member.Name;

    var param = Expression.Parameter(typeof(TEntity), "row");
    var lambda = Expression.Lambda<Func<TEntity, bool>>(
        Expression.Equal(
            Expression.PropertyOrField(param, idName),
            Expression.Constant(id, typeof(TKey))), param);

    return dataContext.GetTable<TEntity>().Single(lambda);
}
Run Code Online (Sandbox Code Playgroud)


p.c*_*ell 3

丹尼斯·特罗勒回答了本在问题评论中链接到的问题。