这些是我的主要课程
public class Customer
{
public Customer()
{
Products = new HashSet<Product>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string ProductName { get; set; }
public Customer Customer { get; set; }
}
这些是我的观点模型
public class ProductVM
{
public string ProductName { get; set; }
}
public class CustomerVM
{
public string Name { get; set; }
public ICollection<ProductVM> Products { get; set; }
}
如何填充CustomerVM
的属性?
我尝试过这样的事情:
var tmp = _db.Customers.Select(c => new CustomerVM
{
Name = c.Name,
Products = ????? // I don't know how to populate here
}
asp.net mvc
和linq
中的新内容仍在向上发展。
答案 0 :(得分:1)
这应该做的工作:
var tmp = _db.Customers.Select(c =>
new CustomerVM
{
Name = c.Name,
Products = c.Products.Select(p => new ProductVM { ProductName = p.ProductName }).ToList()
}
)
答案 1 :(得分:1)
访问Products
媒体资源并使用ProductVM
关键字创建Select
的集合
var customerVm= _db.Customers
.Select(c => new CustomerVM
{
Name = c.Name,
Products = c.Products.
Select(s =>
new ProductVM {ProductName= s.ProductName}).ToList()
});
答案 2 :(得分:1)
如果Products
已填充Customer
:
Products = c.Products.Select(p => new ProductVM() { ProductName = p.ProductName } ).ToList()
如果不是:
Products = _db.Products.Where(p => p.CustomerId = c.Id)
.Select(p => new ProductVM() { ProductName = p.ProductName } ).ToList()
答案 3 :(得分:1)
如果您在客户类中进行ICollection,而在Product类中进行虚拟客户,则会自动链接它们。
public class Customer
{
public Customer()
{
Products = new HashSet<Product>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string ProductName { get; set; }
public virtual Customer Customer { get; set; }
}
如果你这样做,你可以用c.Products填充点数