dotnetnuke2sxc

Linq with strong typed data in 2sxc


This was a common use in dynamic code:

@foreach(var myData in AsList(App.Data["Data"]))
{
    foreach(var x in AsList(myData.Specifications as object).Where(a => a.toApp)) { ... }
}

But in typed data, this always results in one error or another.

@foreach(var myData in App.Data.GetAll<Data>();)
{
    foreach(var x in myData.Specifications).Where(a => a.toApp)) { ... }
}

myData.Specifications is an entity field linking to the data type DataSpecs.

How can these entities data types be properly implemented in strong typed code?


Solution

  • Before RazorTyped, .Specifications would just return an object. Now you need to return either an ITypedItem or IEnumerable<ITypedItem>, since you named it plural, I'll assume the latter.

    So instead try,

        foreach(var x in myData.Children("Specifications")
          .Where( ... )
        ) 
        { 
          ... 
        }
    

    But if its not 1:many, and 1:1 instead, here is an example that I hope makes sense.

    You have a content-type named Project. A field in Project named Client is an Entity pointing to the content-type Clients. So each Project is for 1 Client. Now the Clients content-type has a field named Status (a string dropdown). So now I only want to show Projects for active clients.

    To do this, my where looks like this:

      .Where(p => p.Child("Client").String("Status") == "active")
    

    If another example might help, I also wrote an article a few months back while 2sxc was v16+ but not yet evolved to the newer hotness of things like `.GetAll<Data>(). It shows data relationships and iterating through getting it working, and then using .Parents() to make handling a many:many relationship make sense, be readable, and easy to understand. Its a two part article; part one gets it working minimally, part two goes a lot further.