Siggi
Siggi

Reputation: 69

How do I tell if an object is part of an Entity model?

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.

Upvotes: 3

Views: 351

Answers (2)

Siggi
Siggi

Reputation: 69

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 someList you need to know which types are entities, and which are not. To do that I constructed a list of types from the properties of my 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 which represents my database model (it inherits from DbContext).

This works by locating all the DbSet<T> properties in Entities, and then constructing a collection of all the T types. Each of these types represents an entity type.

To filter someList I simply check if the type of each member is contained in the collection types.

Upvotes: -1

daryal
daryal

Reputation: 14929

This may not seem as a direct answer, but instead of trying to check using DBContext instance, you may just use a Marker interface. Then you may check directly, without using DBContext. For instance,

public interface IEntity
{
}

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

Also, as a side note, I wonder how you are able to store different types of instances in the same List.

Upvotes: 0

Related Questions