如何将值初始化或赋值给类中的集合

时间:2015-01-12 13:47:54

标签: c# asp.net asp.net-mvc asp.net-mvc-viewmodel

如何将视图模型传递给使用构造函数分配属性的类?请参阅我在代码中的评论。

public class Foo 
{
    public Foo() 
    { 
        Bars = new HashSet<Bar>();
    }

    public Foo(FooVm foo) 
    {
        FooId = foo.FooId;
        FooName = foo.FooName;
        // Initialize Bars by passing foo. How? Or is it possible?
    }

    public int FooId { get; set; }
    public string FooName { get; set; }

    public virtual ICollection<Bar> Bars { get; set; }
}

public class Bar 
{
    public Bar() { }

    public Bar(BarVm bar) 
    {
        BarId = bar.BarId;
        BarName = bar.BarName;
    }

    public int BarId { get; set; }
    public string BarName { get; set; }
}

用法:

var fooBar = new Foo(fooVm);

我想要上面的东西。这会初始化Foo类,同时初始化Bars集合,如下所示:

var fooBar = new Foo(fooVm);
fooBar.Bars = fooVm.Bars
                   .Select(b => new Bar { 
                      BarId = b.BarId,
                      BarName = b.BarName });

0 个答案:

没有答案