У меня есть две модели:
Одна для брендов
public class BrandVM
{
public BrandVM() { }
public BrandVM(BrandDTO row)
{
Id = row.Id;
Name = row.Name;
Description = row.Description;
}
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public virtual BicycleVM BicycleVM { get; set; }
}
и вторая для продуктов
public class BicycleVM
{
public BicycleVM() { }
public BicycleVM(BicycleDTO row)
{
Id = row.Id;
CategoryId = row.CategoryId;
BrandId = row.BrandId;
Mark = row.Mark;
Year = row.Year;
Color = row.Color;
ImageName = row.ImageName;
}
public int Id { get; set; }
[DisplayName("Category")]
public int CategoryId { get; set; }
[DisplayName("Brand")]
public int BrandId { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Mark { get; set; }
public int Year { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Color { get; set; }
DisplayName("Image")]
public string ImageName { get; set; }
public string Category { get; set; }
public string Brand { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public IEnumerable<SelectListItem> Brands { get; set; }
public IEnumerable<string> GalleryImages { get; set; }
}
public string Brand {get;задавать;} не существует в таблице, он используется только для просмотра.
Мне нужно как-то получить все бренды из одной таблицы и вставить их в свойство Brand.Идентификатор от Bramds должен совпадать с BrandId.
Как это выглядит для меня: я получаю все названия и идентификаторы бренда из первой таблицы.Сравните BrandId из продуктов с Id в брендах.Если они совпадают, чем product.Brand = brand.Name.
Попробовал это:
List<BicycleVM> listOfBicycleVM;
using (Db db = new Db())
{
var init = db.Bicycles.ToArray()
.Where(x => catId == null || catId == 0 || x.CategoryId == catId)
.Select(x => new BicycleVM(x));
listOfBicycleVM = init.ToList();
var brand = db.Brands.ToList();
listOfBicycleVM.ForEach(bicycle => bicycle.Brand = brand
.FirstOrDefault(p => p.Id == bicycle.BrandId).ToString());
Не повезло: (