Essentially I’m trying to find a less awful way to do this:
foreach (var k in someList)
{
try
{
var temp = Database.Set(k.GetType()).Local;
newList.Add(k);
}
catch (InvalidOperationException)
{
}
}
Database is my DbContext instance for my model.
someList is a collection of objects, some are part of an Entity model, others are not. I want to create a new list (newList) that contains only the objects that are a part of the model. The objects in someList can be of any type (in my case one of these is List<string> which obviously has nothing to do with my underlying database).
The InvalidOperationException is raised when an object from someList is not a part of the Entity model. By doing this I get what I want, however it seems like a hack. I’m looking for a better solution.
I’m adding this answer so that anyone who finds this question can see how I resolved it. That being said, the real solution is to avoid having entities and non-entities in the same collection (as said in the comments to the original question).
To filter the collection
someListyou need to know which types are entities, and which are not. To do that I constructed a list of types from the properties of myDbContext.Entitiesis the class which represents my database model (it inherits fromDbContext).This works by locating all the
DbSet<T>properties inEntities, and then constructing a collection of all theTtypes. Each of these types represents an entity type.To filter
someListI simply check if the type of each member is contained in the collectiontypes.