뭔가를 (GetById을 구현하기 위해이 방법을 사용할 수 있습니다, 기본값은 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);
}
죄송합니다, 내 대답은 좋은 없었다 - 나는 데이터베이스를 조회하는'표'와 객체의 메모리 목록을 혼동. 이 질문은 이전에 여기에 대답했다 : http://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method –