How to convert linq query result to List (Of T)

I am using EntityFrameWork 5 in a VB MV4 project.

I have a database built from an EntityFramework diagram (firt model first, not code)

I have a ViewModel X containing a list of (ofT) T, which is one of my Entity

When I open my web application (in a browser), I ask the controller to provide me with ViewModel X as a Json object, which I use to populate MVKC (knockout model) using the Knockout JS Mapping plugin.

When I request a model, I populate it using code similar to the one shown below

Public Class DataServiceController
    Inherits System.Web.Mvc.Controller

    <Authorize()> _
    Public Function RetrieveData() As JsonResult

        Dim model As ViewModelX
        model = New ViewModelX

    '=====================================
    ' Resources and Tools
    '=====================================
    Dim fetchedResourceAndToolsQuery = From a In db.ResourceAndTools
                       Where a.ProfileId = profile.ProfileId Select a

    For Each eachRes In fetchedResourceAndToolsQuery
        Dim res As ResourceAndTools = New ResourceAndTools
        res.Name = Trim(eachRes.Name)
        res.URL = Trim(eachRes.URL)
        res.Target = eachRes.Target
        res.ResourceId = eachRes.ResourceId
        model.ResourceAndTools.Add(res)
    Next

    Return Json(model, JsonRequestBehavior.AllowGet)

Everthing works great! Except ... And here's the question

As mentioned above, ViewModelX contains a list of (T) T being ResourceAndTools

(, , ) fetchedResourceAndToolsQuery ( Linq) model.ResourceAndTools(List (of T)) , .

(, , ..). , , , , , Entity Framework .

+4
1

?

model.ResourceAndTools = (
    From a In db.ResourceAndTools
    Where a.ProfileId = profile.ProfileId
    Select New ResourceAndTools() With { _
        .Name = Trim(a.Name), _
        .URL = Trim(a.URL), _
        .Target = a.Target, _
        .ResourceId = a.ResourceId}).ToList()

, , ,

Dim dataList = (
    From a In db.ResourceAndTools
    Where a.ProfileId = profile.ProfileId
    Select New With
    {
        .Name = Trim(a.Name),
        .URL = Trim(a.URL),
        .Target = a.Target,
        .ResourceId = a.ResourceId
    }).ToList()

model.ResourceAndTools = dataList.ConvertAll(Function(data)
        Return New ResourceAndTools() With
        {
            .Name = data.Name,
            .Url = data.Url,
            .Target = data.Target,
            .ResourceId = data.ResourceId
        }
    End Function)
+3

Source: https://habr.com/ru/post/1502651/


All Articles