Search code examples
c#entity-frameworkentity-framework-4entity-framework-4.1objectset

ObjectSet.AddObject(T) problem?


The ObjectSet.Single(predicate) doesn't work (the Where() and toList() methods as well) unless i write it this way:

ObjectSet.Cast<TEntity>().Single<TEntity>(predicate)

But i don't know what to do to resolve the problem with the AddObject and DeleteObject methods:

public void Add<TEntity>(TEntity entity)
    {
        ObjectSet.AddObject(entity);
    }

The error message tells me that "entity" is a wrong argument. Is the problem related to EF 4.1?


Solution

  • Here are a few snippets from my generic repository:

    public void Add<K>(K entity) where K : class
    {            
        context.CreateObjectSet<K>().AddObject(entity);
    }
    
    public K SingleOrDefault<K>(Expression<Func<K, bool>> predicate) where K : class
    {
        K entity = context.CreateObjectSet<K>().SingleOrDefault<K>(predicate);
    
        return entity;
    }
    

    Please see the link below: http://msdn.microsoft.com/en-us/library/dd382944.aspx

    Edit: If you already have a created ObjectSet then your class already defines TEntity, therefor your method should be adjusted as such:

    public void Add(TEntity entity)
    {
        ObjectSet.AddObject(entity);
    }
    

    You should also be able to make similar adjustment to your Single() method, there should be no need for a cast.