【问题标题】:How to get a list of navigation properties that implement an interface in entity framework如何获取在实体框架中实现接口的导航属性列表
【发布时间】:2018-02-19 18:02:23
【问题描述】:

在实体框架中,我有一个主类,其中包含 2 个子类的 ICollection 定义。

 public partial class Class1{
      public virtual ICollection<Class2> Class2 {get;set;}
      public virtual ICollection<Class3> Class3 {get;set;}
 }

 public partial class Class2 : ITotal {
      public double Total {get;}
 }

 public partial class Class3 {

 }

Class2 实现了 ITotal 接口...Class3 没有。

Class1 总共有大约 30 个 ICollections 实例,其中基础对象实现了 ITotal 接口。它还有 10 多个不实现接口的 ICollections。

在 Class1 中,我需要能够动态获取其基类型实现 ITotal 接口的所有 ICollections。然后我将添加“总计”字段以获得总体总计。我需要它是动态的原因是因为我将向 class1 添加更多的 ICollections,并且我不想/不需要记住去多个地方以获得准确的总数。

下面是我到目前为止的一个示例......这段代码为我提供了所有 ICollection 类,但现在我被卡住了。理想情况下,我可以在最后一次选择之后添加另一个 where 子句,但我愿意完全放弃它。

 var value1 = t.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                          .Where(x => x.CanWrite && x.GetGetMethod().IsVirtual)
                          .Select(x => x.GetValue(this, null))
                          .Where(x => x != null)
                          .Where(x => x.GetType().GetInterfaces().Any(y => y.IsGenericType && y.GetGenericTypeDefinition() == typeof(ICollection<>)))
                          .Select(x=> ((IEnumerable)x))
                          .ToList()
                          ;

有什么想法吗?

【问题讨论】:

    标签: entity-framework reflection interface


    【解决方案1】:

    像这样:

            var c = new Class1();
    
            //. . .
    
            var q = from p in typeof(Class1).GetProperties()
                    where p.PropertyType.IsConstructedGenericType
                       && p.PropertyType.GetGenericTypeDefinition().Equals(typeof(ICollection<>))
                       && typeof(ITotal).IsAssignableFrom(p.PropertyType.GetGenericArguments()[0])
                    select p;
    
            var ITotalCollections = q.ToList();
    
            var q2 = from p in ITotalCollections
                     from i in (IEnumerable<ITotal>)p.GetValue(c)
                     select i.Total;
    
            var total = q2.Sum();
    

    【讨论】:

    • 完美运行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多