如何将视图模型传递给使用构造函数分配属性的类?请参阅我在代码中的评论。
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 });