c# - 从一个模型获取名称到另一个模型
问题描述
我有两个模型:
一个是品牌
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; }
}
公共字符串品牌{获取;放; } 表中不存在,仅用于查看。
我需要以某种方式从一张表中获取所有品牌并将它们插入到属性品牌中。Bramds 的 ID 必须与 BrandId 匹配。
对我来说是怎样的:我从第一个表中获取了所有品牌的名称和 ID。将产品中的 BrandId 与 Brands 中的 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());
没运气 :(
解决方案
您不应该尝试将两者组合ViewModels
在一起以获得一个视图,这违背了它们的目的。但是,您可以将两个模型组合成一个ViewModel
.
创建一个ViewModel
包含所有所需数据的单曲,并将其命名为“BicycleBrandVM”。在控制器中填充它,或者在你ViewModels
刚才填充的地方填充它,然后将它传递给你的View
.