2

I am trying to convert anonymous types to list but i am getting invocation errors like below.

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

var all = from a in Fcticuclist
          join b in crlist on a.Ref_CID equals b.C_ID
          select new { b.MU_Identifier, a.Status,a.ID };

foreach (var item in all)
{
    castapprove.Add(new muapprovelist { Id = item.ID, MU_Identifier = item.MU_Identifier, Status = item.Status });
}

so here "all" is anonymous type and castapprove is a list and muapprovelist is a class and they are declared in the same view model. Any pointers where i am doing it wrong ?

6
  • 2
    how is castapprove declared? what kind of list is it? are you perhaps using dynamic? My guess here is that you have dynamic castapprove = ... in which case... yeah, I wouldn't expect it to work. Commented Feb 1, 2018 at 10:31
  • 2
    The TargetInvocationException normally has an InnerException that explains what really went wrong (and where). Please post that information, too. Is muapprovelist the correct type for elements in that list (because it sounds like a list itself)? Commented Feb 1, 2018 at 10:31
  • Shouldn't new { b.MU_Identifier, a.Status,a.ID } be new{MU_Identifier = b.MU_Identifier, Status = aStatus , ID = a.Status,a.ID }? Commented Feb 1, 2018 at 10:33
  • @ZoharPeled that's no problem, you don't need to specify names, the compiler takes the names of the properties you give (MU_Identifier, Status and ID in this case). Commented Feb 1, 2018 at 10:34
  • @RenéVogt Thanks, I wasn't sure about that. Commented Feb 1, 2018 at 10:35

1 Answer 1

3

Presumably this is some accessibility issue relating to dynamic compilation of a view of some kind and the anonymous type (which is internal). Perhaps a pragmatic solution is to not use the anonymous type in this case:

var all = from a in Fcticuclist
      join b in crlist on a.Ref_CID equals b.C_ID
      select new muapprovelist {
          Id = a.ID, MU_Identifier = b.MU_Identifier,
          Status = a.Status };

foreach (var item in all)
{
    castapprove.Add(item);
}

Perhaps even:

var castapprove = (from a in Fcticuclist
      join b in crlist on a.Ref_CID equals b.C_ID
      select new muapprovelist {
          Id = a.ID, MU_Identifier = b.MU_Identifier,
          Status = a.Status }).ToList();

Alternatively: move this code away from the view area into code that is part of the main pre-compiled assembly.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried the second solution and it worked, Thank you so much. That was a good learning for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.