从列表<vm>中创建新列表<t>

时间:2017-03-09 15:35:44

标签: c# asp.net entity-framework linq

我目前正在使用EF 6处理ASP.NET MVC 4.5应用程序。目前我正在使用linq查询将数据存储在带有Entity Framework的数据库中。

我的问题:在查询 SwotParts 中,我需要创建一个List<T>,其中包含两个List<VM>。因此,将两个相同类型的列表合并为一个新列表。

我的查询如下:

SWOT = vm.Swots.Select(x => new SWOT
{
    SwotForId = x.SwotForId,
    SwotParts = x.ExternalSwotParts.Select(y => new SwotPart
    {
        SwotTypeId = y.SwotTypeId,
        Label = y.Label
    },
    x.InternalSwotParts.Select(z => new SwotPart
    {
        SwotTypeId = z.SwotTypeId,
        Label = z.Label
    })).ToList()       
}).ToList()

显然这不起作用,但我希望它显示出基本的想法......

这是我的班级 SWOT

public partial class SWOT
{
    public SWOT()
    {
        this.SwotPart = new HashSet<SwotPart>();
    }

    public int SwotId { get; set; }
    public SwotFor SwotForId { get; set; }

    public virtual ICollection<SwotPart> SwotPart { get; set; }
}

SwotVm

public class SwotVm
{
    // enum
    public SwotFor SwotForId { get; set; }
    public List<SwotPartVm> InternalSwotParts { get; set; }
    public List<SwotPartVm> ExternalSwotParts { get; set; }
}

和我的班级 SwotPart

public partial class SwotPart
{
    public byte SwotPartId { get; set; }
    public SwotType SwotTypeId { get; set; }
    public string Label { get; set; }
}

谢谢!

4 个答案:

答案 0 :(得分:1)

有一种内置方法.ConvertAll()可以帮助解决这种情况。

//merge the two existing lists
oldList1.AddRange(oldList2);

//make a new one converted into the new type
var newList = oldList1.ConvertAll(
    (originalElement) => new Blah(originalElement.Property)
);

答案 1 :(得分:0)

self.view.addSubview(pageMenu!.view)

首先要注意的是,您需要告诉EF您希望在原始查询中包含ExternalSwotParts和InternalSwotParts,以便内部select语句不会通过EF延迟加载导致其他查询。

然后,我们在select之前调用addChildViewController(pageMenu!) self.view.addSubview(pageMenu!.view) pageMenu!.didMove(toParentViewController: self) ,这会导致EF立即执行SQL查询并将所有Swots和SwotPart加载到内存中。然后我们可以在内部进行任何选择,因为所有数据现在都在内存中。

答案 2 :(得分:0)

您必须在MVVM对象中定义VM。

public class CreateModelHouseViewModel
{
    public CreateModelHouseViewModel()
    {
    }
    public CreateHouseViewModel House { get; set; }
    public CreateAddressViewModel Billing { get; set; }    
}

// sample

var vm = new CreateModelHouseViewModel();

var pocoEntity = new PocoEfModel {propA=vm.House.propA};

//实体列表

var pocoEntityList = new List<PocoEfModel>();
pocoEntityList.Add(New PocoEfModel {propA=vm.House.propA};

我希望这有帮助!

答案 3 :(得分:-1)

您需要的只是Concat()方法,它将两个序列合并为一个。

E.g:

SWOT = vm.Swots.Select(x => new SWOT
{
    SwotForId = x.SwotForId,
    SwotParts = x.ExternalSwotParts.Select(y => new SwotPart
    {
        SwotTypeId = y.SwotTypeId,
        Label = y.Label
    }).Concat(
    x.InternalSwotParts.Select(z => new SwotPart
    {
        SwotTypeId = z.SwotTypeId,
        Label = z.Label
    })).ToList()       
}).ToList()