2009-03-30 16 views
11

Estoy intentando crear un repositorio de genéricos muy genérico para mi repositorio de Entity Framework que tiene las instrucciones CRUD básicas y utiliza una interfaz. Primero he golpeado una pared de ladrillo y he sido derribado. Aquí está mi código, escrito en una aplicación de consola, usando un Entity Framework Model, con una tabla llamada Hurl. Simplemente tratando de retirar el objeto por su ID. Aquí está el código completo de la aplicación.Error de repositorio genérico de Entity Framework

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.Objects; 
using System.Linq.Expressions; 
using System.Reflection; 
using System.Data.Objects.DataClasses; 

namespace GenericsPlay 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var hs = new HurlRepository(new hurladminEntity()); 
      var hurl = hs.Load<Hurl>(h => h.Id == 1); 
      Console.Write(hurl.ShortUrl); 
      Console.ReadLine(); 

     } 
    } 

    public interface IHurlRepository 
    { 
     T Load<T>(Expression<Func<T, bool>> expression); 
    } 

    public class HurlRepository : IHurlRepository, IDisposable 
    { 

     private ObjectContext _objectContext; 

     public HurlRepository(ObjectContext objectContext) 
     { 
      _objectContext = objectContext; 
     } 

     public ObjectContext ObjectContext 
     { 
      get 
      { 
       return _objectContext; 
      } 
     } 

     private Type GetBaseType(Type type) 
     { 
      Type baseType = type.BaseType; 
      if (baseType != null && baseType != typeof(EntityObject)) 
      { 
       return GetBaseType(type.BaseType); 
      } 
      return type; 
     } 

     private bool HasBaseType(Type type, out Type baseType) 
     { 
      Type originalType = type.GetType(); 
      baseType = GetBaseType(type); 
      return baseType != originalType; 
     } 

     public IQueryable<T> GetQuery<T>() 
     { 
      Type baseType; 
      if (HasBaseType(typeof(T), out baseType)) 
      { 
       return this.ObjectContext.CreateQuery<T>("[" + baseType.Name.ToString() + "]").OfType<T>(); 
      } 
      else 
      { 
       return this.ObjectContext.CreateQuery<T>("[" + typeof(T).Name.ToString() + "]"); 
      } 
     } 

     public T Load<T>(Expression<Func<T, bool>> whereCondition) 
     { 
      return this.GetQuery<T>().Where(whereCondition).First(); 
     } 

     public void Dispose() 
     { 
      if (_objectContext != null) 
      { 
       _objectContext.Dispose(); 
      } 
     } 
    } 

} 

Aquí está el error que estoy recibiendo:

System.Data.EntitySqlException was unhandled 
    Message="'Hurl' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near escaped identifier, line 3, column 1." 
    Source="System.Data.Entity" 
    Column=1 
    ErrorContext="escaped identifier" 
    ErrorDescription="'Hurl' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly." 

Aquí es donde yo estoy tratando de extraer esta información de.

http://blog.keithpatton.com/2008/05/29/Polymorphic+Repository+For+ADONet+Entity+Framework.aspx

+0

supongo una respuesta más corta es donde podría yo ir a iniciar la depuración de este problema. –

Respuesta

6

Bueno, éste me había intrigado. Tomé una puñalada salvaje (después de ver una porción del EFRepository en el próximo libro ASP.NET MVC Unleashed de Stephen Walther) y comenzó a funcionar, aquí está la solución (Reemplace este método, note la diferencia en el formato de cadena). ¿Alguna sugerencia de por qué esto es así? La forma en que veo esto, puede ser un error (o tal vez algo que estaba haciendo). En cualquier caso, para cualquiera de los interesados. (Me imagino que arreglar esta porción arreglará la función completa de EFRepository @Keith Patton's blog post).

public IQueryable<T> GetQuery<T>() 
{ 
    Type baseType; 
    if (HasBaseType(typeof(T), out baseType)) 
    { 
     return this.ObjectContext.CreateQuery<T>(String.Format("[{0}]", baseType.Name.ToString())).OfType<T>(); 
    } 
    else 
    { 
     return this.ObjectContext.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString())); 
    } 
} 
+0

Acabo de llegar a casa para probar y la solución completa no funcionó hasta DESPUÉS de que agregué esto. String.Format ("[{0} Set]", (Donde corresponda en la solución anterior). –

+1

Para obtener el nombre sin hardcoding algo como '" [{0} Establecer "]', vea mi publicación en otra pregunta: http : //stackoverflow.com/questions/3247288/error-in-generic-repository-method-for-entity-framework/3247456#3247456 – TheCloudlessSky

Cuestiones relacionadas