0

我为我的 EF 上下文提供了扩展,以包含所有具有的Mission实体属性RequiredAttribute

public static IQueryable<Mission> MissionWithRequired(this IDbContext context)
{
   return context.Missions
             .Include(mission => mission.Theme)
             .Include(mission => mission.Contact)
             .Include(mission => mission.Editor);
}

它工作正常。

重构它的想法 - 使其不仅可以与其他实体一起使用,Missions而且还可以与其他实体一起使用。

我的第一步是阅读标有RequiredAttributeusing的属性Reflection。但它不起作用:

public static IQueryable<Mission> MissionWithRequired(this IOrgDatenbankContext context)
{
   var requiredProperties = typeof(Mission).GetProperties()
            .Where(property => Attribute.IsDefined(property, typeof(RequiredAttribute)));

   foreach (var requiredProperty in requiredProperties)
   {
      context.Missions.Include(requiredProperty.Name);
   }

   return context.Missions;
}

context包含Missions但不Theme包含,Contract并且Editor

4

1 回答 1

1

尝试将每个包含保存到一个局部变量中(抱歉,我无法验证它是否有效)

public static IQueryable<Mission> MissionWithRequired(this IOrgDatenbankContext context)
{
   var requiredProperties = typeof(Mission).GetProperties()
            .Where(property => Attribute.IsDefined(property, typeof(RequiredAttribute)));

   IQueryable<Mission> result = context.Missions;
   foreach (var requiredProperty in requiredProperties)
   {
      result = result.Include(requiredProperty.Name);
   }

   return result;
}
于 2013-06-20T13:14:45.997 回答