Akli
Akli

Reputation: 1539

Unable to cast object of type 'System.Data.Entity.DbSet`1[ModelName]' to type 'System.Data.Entity.DbSet'

My Entityframework context :

public class MyContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<Event> Events { get; set; }        
}

My method to add objects:

public void AddObject(DbContext context, Type t, object object_to_add)
{      
     PropertyInfo context_property = 
            context.GetType().GetProperties()
           .Where(p => typeof(IEnumerable).IsAssignableFrom(p.PropertyType)
                       && p.PropertyType.GenericTypeArguments.Any()
                       && p.PropertyType.GenericTypeArguments.First() == t)
           .Single();

     DbSet db_set = (DbSet)context_property.GetMethod.Invoke(context, null);

     db_set.Add(object_to_add);
}

But the code crashes when I try to cast a DbSet<> to DbSet,

I'm using reflection because I receive DTO objects that I map to an existing model(via reflection as well), I don't want to code an add method for each new model (I have like 40 and the list is exponentially growing)

Blockquote

Any solution?

Upvotes: 2

Views: 4173

Answers (2)

user848765
user848765

Reputation:

Using reflection in a production environment will yield a poor performance. So octaviocci's method is better in every way.

However if you cannot make your method generic, you can try

public void AddObject(DbContext context, Type t, object object_to_add)
{
   context.Set(t).Add(object_to_add);
}

You are getting InvalidCastException because System.Data.Entity.DbSet<TEntity> does not implement System.Data.Entity.DbSet.

See the definition on https://msdn.microsoft.com/en-us/library/gg696460(v=vs.113).aspx

public class DbSet<TEntity> : DbQuery<TEntity>, IDbSet<TEntity>, 
    IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable

Upvotes: 3

ocuenca
ocuenca

Reputation: 39326

I think is easier if you create a generic method:

public void AddObject<T>(DbContext context,  T object_to_add)
{
   context.Set<T>().Add(object_to_add);
}

Yo can use Set<TEntity> method as I show above.

Upvotes: 7

Related Questions