Justin
Justin

Reputation: 627

Wrapping A EF Method

I asked a previous question where this code was provided to me:

public void AddRecord<T>(params T[] items) where T : class
{
    var set = Set<T>();
    foreach (var item in items)
        set.Add(item);
}

Now, this is great however, I would like to call this method from inside another method. Where I can determine if I need to add or update a record.

I tried this: public void AddNewRec(Object entity, bool add) however an exception is thrown: entity type Object is not part of the model for the current context. What is going on? What is the parameter type I should have for entity then in the wrapper method? So confused.

Upvotes: 0

Views: 76

Answers (1)

Jeremy Todd
Jeremy Todd

Reputation: 3289

What's happening is that your entity parameter is of type Object, so when you pass it to your generic AddRecord<T> method, T becomes Object. Then, within that method, Set<T>() becomes Set<Object>(), and since Object isn't one of your entity types, your context can't find a DbSet for it, and it barfs.

You should be able to get it working by changing your AddNewRec method to a generic method instead of passing it an Object: try AddNewRec<T>(T entity, bool add) where T : class. That should allow your entity type to filter down to your AddRecord<T> method.

Upvotes: 2

Related Questions