2009-08-08 92 views
5

我正在寫一個LINQ to SQL的基礎知識庫,我希望允許GetByID和一個int參數。簽名是:使用LINQ to SQL確定主鍵

public T GetByID(int id) 
{ 
    // Return 
    return _dataContext.GetTable<T>() ....; 
} 

我的表具有不同的主鍵名稱。我想要做的是爲每個T動態地確定主鍵是什麼,並查詢它的值爲integer = id。任何想法如何最好地把這個關掉?

+0

對不起,我的答案是沒有好 - 我困惑的對象在內存中的列表,並附有表'',其查詢數據庫。此問題以前在這裏回答:http://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method – 2009-08-08 18:39:22

回答

3

就我個人而言,我認爲提供採用Func<int,T>選擇器參數的SingleOrDefault<T>方法會更容易。然後,您可以提供您希望的任何選擇器,包括根據該表的ID選擇的選擇器。

public abstract class Repository<T> where T : class 
{ 
    public abstract T GetById(int id); 
    public T SingleOrDefault(Func<int,T> selector) 
    { 
      return _dataContext.GetTable<T>().SingleOrDefault(selector); 
    } 
} 

用法:

var myObj = repos.SingleOrDefault<MyClass>(c => c.MyClassID == id); 

強類型的程序存儲庫可再使用這種方法來實現GetById()

public class MyClassRepository : Repository<MyClass> 
{ 
    public override MyClass GetById(int id) 
    { 
     return this.SingleOrDefault(c => c.MyClassID == id); 
    } 
} 
+0

難道你沒有忘記實際檢查傳入的ID對'c.MyClassID'的值? – GregL 2011-03-22 01:37:12

+0

@GregL - 好。固定。 – tvanfosson 2011-03-22 02:21:18

10

類似下面(支持其他類型的不僅僅是int,但默認爲int)。重要的是,不要陷入通過反思來看待Attribute數據的陷阱; LINQ到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); 
} 
+0

這絕對是最好的方法,也是一個很好的答案,因爲它指出了LINQ to SQL的一個不太知名的功能(運行時元數據)。 – 2009-08-09 02:31:21