lundi 11 septembre 2017

How to get a list of navigation properties that implement an interface in entity framework

In the entity framework, I have a main class with ICollection definitions for 2 sub classes.

 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 implements the ITotal interface...Class3 does not.

In total Class1 has about 30 instances of ICollections where the base object implements the ITotal interface. It also has 10+ ICollections that do not implement the interface.

Within Class1, I need to be able to dynamically get all ICollections whose base type implement the ITotal interface. Then I will add the "Total" fields to get an overall total. The reason I need it to be dynamic is because I will be adding many more ICollections to class1 and I don't want/need to have to remember to go to multiple places to get the totals to be accurate.

Below is a sample of what I have so far...this bit of code gives me all the ICollection classes, but now I am stuck. Ideally, I could add another where clause after the last select, but I am open to scrapping it altogether.

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

Any thoughts?





Aucun commentaire:

Enregistrer un commentaire