loop through all entities with LINQ to Entities

712 views Asked by At

I have n entities and some of them have a property that with the same name in all of them.

Is there a way in Linq to Entities where I can loop through all my entities and check on whether they have a property and if they do then do something with them?

I want to do this (pseudo code)

foreach(var entity in myEntities.entities)
{
    If (entity has property)
    {
        Var query = from q in entity where property= “99” select q;
        ….
    }
}

EDIT:

I guess another way of saying this is that instead of doing this:

var cars = from c in Entities.Cars where Colour = "white" select c;
var fruits = from f in Entities.Fruits where Colour = "white" select f;
....

I want to be able to do something like this (pseudo-code):

var colouredEntities = GetAllEntitiesThatContainPropertyColour();
foreach(var colouredEntity in colouredEntities)
{
     var entity= from f in Entities.colouredEntity where Colour = "white" select e;
}
1

There are 1 answers

2
DotNetHitMan On

So to achieve the 'if (entity has property)' can be achieved via reflection.

The following code would check whether the entity has a property with a foreign key attribute.

var hasKey = (from prop in entity.GetType().GetProperties() where Attribute.IsDefined(prop, typeof(ForeignKeyAttribute)) == true select true).FirstOrDefault();

If you wanted to do it by name then the following code would suffice.

var hasName = (from prop in entity.GetType().GetProperties() where prop.Name == "APropertyOfYourChoosing" select true).FirstOrDefault();