1

我有一个通用的存储库中,我尝试添加GetById方法,如下所示 C# LINQ to SQL: Refactoring this Generic GetByID method通用仓库EF4 CTP5 getById

的问题是我的仓库不使用System.Data.Linq.DataContext ,而不是我用System.Data.Entity.DbContext

所以我得到的错误,我尝试使用

Mapping.GetMetaType 

return _set.Where(whereExpression).Single(); 

我如何能实现在CTP5通用GetById方法?我应该在我的Repository中使用System.Data.Entity.DbContext。

这里是我的仓库类的开始

public class BaseRepository<T> where T : class 
    { 

     private DbContext _context; 
     private readonly DbSet<T> _set; 

     public BaseRepository() 
     { 
      _context = new MyDBContext(); 
      _set = _context.Set<T>(); 

     } 

回答

9

最基本的方法是简单地

public T GetById(params object[] keys) 
{ 
    _set.Find(keys); 
} 

如果你知道你的所有实体具有名为id的主键(它没有在数据库中称为Id但它必须映射到属性Id),您可以简单地使用此定义类型:

public interface IEntity 
{ 
    int Id { get; } 
} 

public class BaseRepository<T> where T : class, IEntity 
{ 
    ... 

    public T GetById(int id) 
    { 
    _set.Find(id); 
    } 
} 

如果数据类型并不总是相同的,你可以使用:

public interface IEntity<TKey> 
{ 
    TKey Id { get; } 
} 

public class BaseRepository<TEntity, TKey> where TEntity : class, IEntity<TKey> 
{ 
    ... 

    public TEntity GetById(TKey id) 
    { 
    _set.Find(id); 
    } 
} 

你也可以简单地使用:

public class BaseRepository<TEntity, TKey> where TEntity : class 
{ 
    ... 

    public TEntity GetById(TKey id) 
    { 
    _set.Find(id); 
    } 
} 
+0

优秀,感谢解释许多方法。他们似乎都做工精细除了_set.FindBy我找不到System.Data.Entity.DBSet – Daveo 2011-03-02 21:08:15

+0

这种方法是错字:)它应该是'Find' – 2011-03-02 21:23:05

+0

@Ladislav Mrnka:在你的第一个例子,在那里你提供PARAMS对象[]键到GetById方法,如果有两个字段作为主键,那么如何映射Find每个键到相关字段? – Naor 2011-04-25 21:58:11

1

试试这个

public virtual T GetByID(object id) 
    { 

     // Define the entity key values. 
     IEnumerable<KeyValuePair<string, object>> entityKeyValues = 
      new KeyValuePair<string, object>[] { 
      new KeyValuePair<string, object>("Id", id) }; 

     string qualifiedEntitySetName = _context.DefaultContainerName + "." + typeof(T).Name; 
     EntityKey key = new EntityKey(qualifiedEntitySetName, entityKeyValues); 

     return (T)_context.GetObjectByKey(key);   
    }