कुछ नीचे की तरह (जो सिर्फ int
के अलावा अन्य प्रकार का समर्थन करता इस विधि का उपयोग कर सकता है, लेकिन int
पर डिफ़ॉल्ट)। महत्वपूर्ण बात यह है कि प्रतिबिंब के माध्यम से Attribute
डेटा देखने के जाल में मत आना; LINQ करने वाली एसक्यूएल भी गुण के बिना वस्तुओं का समर्थन करता है:
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);
}
स्रोत
2009-08-08 19:23:10
क्षमा करें, मेरा उत्तर अच्छा नहीं था - मैं एक 'टेबल', जो डेटाबेस प्रश्नों के साथ वस्तुओं का इन-स्मृति सूची उलझन में। इस प्रश्न का पहले यहां उत्तर दिया गया था: http://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method –