LINQ error invalid initializer member declarator

后端 未结 1 1560
庸人自扰
庸人自扰 2021-01-23 17:17

I\'m a fairly junior C# developer so excuse me if this is trivial, but I am coming up with this error \"invalid initializer member declarator\" at the line of code I indicate be

1条回答
  •  醉话见心
    2021-01-23 17:45

    You can't access complex object properties in a class initializer like that (as you are attempting with the PODetail.POHeaderId property). You might have to implement a small workaround: create a collection of anonymous objects with the information you have already, then reconstruct a concrete list of PODetailsListViewModels right afterwards:

    var contactGrid = from l in poDetails.ToList()
                      select new {
                      {
                           Id = l.Id,
                           POHeaderId = l.POHeaderId
                           ...
                      };
    

    And then you can manually recreate what you're looking for:

    var someNewCollection = New List(Of PODetailsListViewModel);
    foreach (var item in contactGrid)
        var model = new PODetailsListViewModel()
        {
             Id = item.Id
        };
        model.PODetail = new PODetailModel() /* replace with actual class name */
        {
            POHeaderId = item.POHeaderId
        };
        someNewCollection.Add(model);
    }
    return someNewCollection;
    

    EDIT: Or perhaps you could nest the initializers:

    var contactGrid = from l in poDetails.ToList()
                      select new PODetailsListViewModel() {
                      {
                           Id = l.Id,
                           PODetail = new PODetailModel()
                           {
                               POHeaderId = l.POHeaderId
                           },
                           ...
                      };
    

    0 讨论(0)
提交回复
热议问题