我有n个实体,其中一些实体有一个属性,所有实体都有相同的名称。
是否有一种方法在Linq到实体,我可以循环通过所有我的实体,并检查他们是否有一个属性,如果他们这样做,然后与他们做一些事情?
我想这样做(伪代码)
foreach(var entity in myEntities.entities)
{
If (entity has property)
{
Var query = from q in entity where property= “99” select q;
….
}
}
编辑:我想另一种说法是:
var cars = from c in Entities.Cars where Colour = "white" select c;
var fruits = from f in Entities.Fruits where Colour = "white" select f;
....
我希望能够做这样的事情(伪代码):
var colouredEntities = GetAllEntitiesThatContainPropertyColour();
foreach(var colouredEntity in colouredEntities)
{
var entity= from f in Entities.colouredEntity where Colour = "white" select e;
}
所以要实现'if (entity has property)'可以通过反射来实现。
下面的代码将检查实体是否具有带有外键属性的属性。
var hasKey = (from prop in entity.GetType().GetProperties() where Attribute.IsDefined(prop, typeof(ForeignKeyAttribute)) == true select true).FirstOrDefault();
如果您想按名称执行,那么下面的代码就足够了。
var hasName = (from prop in entity.GetType().GetProperties() where prop.Name == "APropertyOfYourChoosing" select true).FirstOrDefault();