简体   繁体   中英

how can i populate my viewmodel's property with collection in it?

These are my main class

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; }
}

These are my view models

public class ProductVM
{
  public string ProductName { get; set; }
}

public class CustomerVM
{
  public string Name { get; set; }
  public ICollection<ProductVM> Products { get; set; }
}

How can I populate the properties of CustomerVM ?

Something like this I have tried:

var tmp = _db.Customers.Select(c => new CustomerVM
{
  Name = c.Name,
  Products = ????? // I don't know how to populate here
}

Really new in asp.net mvc and linq still making my way up.

This should do the work:

var tmp = _db.Customers.Select(c =>
    new CustomerVM
    {
        Name = c.Name,
        Products = c.Products.Select(p => new ProductVM { ProductName = p.ProductName }).ToList()
    }
)

Access the Products property and Create a collection of ProductVM from that using the Select keyword like this

var customerVm= _db.Customers
                   .Select(c => new CustomerVM
                                {
                                  Name = c.Name,
                                  Products = c.Products.
                                                  Select(s => 
                                    new ProductVM {ProductName= s.ProductName}).ToList()
                                });

If the Products is already populated in the Customer :

Products = c.Products.Select(p => new ProductVM() { ProductName = p.ProductName } ).ToList()

If not :

Products = _db.Products.Where(p => p.CustomerId = c.Id)
    .Select(p => new ProductVM() { ProductName = p.ProductName } ).ToList()

If you make your ICollection in the Customer Class and the Customer in the Product class virtual you will have them linked automatically.

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; }
}

if you do so you can fill the dots with c.Products

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM