generic repository EF4 CTP5 getById

前端 未结 2 531
无人共我
无人共我 2020-12-06 08:30

I have a generic repository an I am trying to add a GetById method as shown here C# LINQ to SQL: Refactoring this Generic GetByID method

The problem is my repository

相关标签:
2条回答
  • 2020-12-06 09:21

    The most basic approach is simply

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

    If you know that all your entities have primary key called Id (it doesn't have to be called Id in DB but it must be mapped to property Id) of defined type you can use simply this:

    public interface IEntity
    {
      int Id { get; }
    }
    
    public class BaseRepository<T> where T : class, IEntity
    {
      ...
    
      public T GetById(int id)
      {
        _set.Find(id);
      }
    }
    

    If data type is not always the same you can use:

    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);
      }
    }
    

    You can also simply use:

    public class BaseRepository<TEntity, TKey> where TEntity : class
    {
      ...
    
      public TEntity GetById(TKey id)
      {
        _set.Find(id);
      }
    }
    
    0 讨论(0)
  • 2020-12-06 09:24

    try this

        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);           
        }
    
    0 讨论(0)
提交回复
热议问题