How to determine if an object is part of an Entity model?

Basically I'm trying to find a less terrible way to do this:

foreach (var k in someList)
{
    try
    {
        var temp = Database.Set(k.GetType()).Local;
        newList.Add(k);
    }
    catch (InvalidOperationException)
    {

    }
}

      

Database

- my copy DbContext

for my model.

someList

is a collection of objects, some are part of the Entity model, others are not. I want to create a new list ( newList

) that only contains objects that are part of the model. Objects in someList

can be of any type (in my case, one of them List<string>

, which obviously has nothing to do with my underlying database).

InvalidOperationException

occurs when the object from is someList

not part of the Entity model. By doing this I get what I want, however it seems like a hack. I am looking for the best solution.

+3


source to share


2 answers


I am adding this answer so that anyone who has found this question can see how I have 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 a collection someList

, you need to know which types are objects and which are not. For this I built a list of types from my properties DbContext

.

types = (from t in typeof (Entities).GetProperties()
         where t.PropertyType.IsGenericType
         where
             t.PropertyType.GetGenericTypeDefinition() ==
             typeof (DbSet<object>).GetGenericTypeDefinition()
         select t.PropertyType.GetGenericArguments()[0]).Distinct();

      



Entities

is the class that represents my database model (it inherits from DbContext

).

It works by finding all properties DbSet<T>

in Entities

and then building a collection of all types T

. Each of these types represents an entity type.

To filter someList

, I just check if the type of each item is contained in the collection types

.

0


source


This may not seem like a straightforward answer, but instead of checking for instance usage DBContext

, you can simply use the Marker interface. Then you can check directly without using DBContext

. For example,

public interface IEntity
{
}

public clas SomeEntity : IEntity
{
    ... some properties
}

      



Also, as a side note, I wonder how you can store different types of instances in the same list.

+1


source







All Articles