I am trying to create a general class for working with objects from EF. This class speaks to repositories, but this class creates expressions sent to the repositories. Anyway, I'm just trying to implement one virtual method, which will serve as the basis for a general request. In particular, he will accept a int, and he only needs to fulfill the request for the first key of the object in question.
I pondered this, and I created a reflection that may or may not work. I say that since I receive a message NotSupportedExceptionwith the LINQ to Entities message, the method 'System.Object GetValue (System.Object, System.Object [])' does not recognize, and this method cannot be translated into the expression store. So, I tried a different approach and it threw the same exception, but with LINQ expression error node type 'ArrayIndex' is not supported in LINQ to Entities. I know this because EF will not parse the expression the way L2S will.
In any case, I will jump that someone with a little more experience can point me in the right direction. I am posting the whole class on both the attempts I made.
public class Provider<T> where T : class {
protected readonly Repository<T> Repository = null;
private readonly string TEntityName = typeof(T).Name;
[Inject]
public Provider(
Repository<T> Repository) {
this.Repository = Repository;
}
public virtual void Add(
T TEntity) {
this.Repository.Insert(TEntity);
}
public virtual T Get(
int PrimaryKey) {
return this.Repository.Select(
t =>
(((int)(t as EntityObject).EntityKey.EntityKeyValues[0].Value) == PrimaryKey)).Single();
return this.Repository.Select(
t =>
(((int)t.GetType().GetProperties().Single(
p =>
(p.Name == (this.TEntityName + "Id"))).GetValue(t, null)) == PrimaryKey)).Single();
}
public virtual IList<T> GetAll() {
return this.Repository.Select().ToList();
}
protected virtual void Save() {
this.Repository.Update();
}
}
UPDATE for @Gabe
Here's what my repository class looks like:
public class Repository<T> where T : class {
protected readonly ObjectContext ObjectContext = null;
private readonly IObjectSet<T> ObjectSet = null;
[Inject]
public Repository(
ObjectContext ObjectContext) {
this.ObjectContext = ObjectContext;
this.ObjectSet = this.ObjectContext.CreateObjectSet<T>();
}
public virtual void Delete(
T Entity) {
this.ObjectSet.DeleteObject(Entity);
}
public virtual void Insert(
T Entity) {
this.ObjectSet.AddObject(Entity);
}
public virtual IQueryable<T> Select() {
return this.ObjectSet;
}
public virtual IQueryable<T> Select(
Expression<Func<T, bool>> Selector) {
return this.ObjectSet.Where(Selector);
}
public virtual void Update() {
this.ObjectContext.SaveChanges();
}
}
SQL, LINQ, , , .