是否可以在上下文中仅包含必需的属性?

时间:2013-06-20 11:26:52

标签: c# entity-framework reflection ef-code-first

我的EF上下文扩展包含了Mission的{​​{1}}实体的所有属性:

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阅读标有RequiredAttribute的属性。但它不起作用:

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但不包含MissionsThemeContract

1 个答案:

答案 0 :(得分: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;
}