使用LINQ to Entities循环遍历所有实体

时间:2015-06-09 08:23:34

标签: .net linq entity-framework linq-to-entities

我有n个实体,其中一些实体的属性名称相同。

在Linq to Entities中是否有办法可以遍历我的所有实体并检查它们是否有属性,如果有,那么就用它们做一些事情?

我想这样做(伪代码)

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;
}

1 个答案:

答案 0 :(得分:0)

所以要实现“如果(实体有财产)'可以通过反思来实现。

以下代码将检查实体是否具有具有外键属性的属性。

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();