我有以下模特:其中有多对多关系。
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
public string Code { get; set; }
[MaxLength(1000)]
public string Description { get; set; }
public string ImageUrl { get; set; }
[Required]
public double Price { get; set; }
public decimal Cost { get; set; }
public bool IsActive { get; set; }
public ICollection<ProductCategory> ProductCategories { get; set; }
}
public class ProductCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
public string Code { get; set; }
[MaxLength(1000)]
public string Description { get; set; }
public string CategoryImgeUrl { get; set; }
public ICollection<Product> Products { get; set; }
}
我想在现有类别中添加新产品,但是当我添加新产品时,我也会在不使用现有产品的情况下创建新类别。
public void Add(ProductViewModel vm)
{
try
{
if (vm.SelectedCategoryIds.Count() != 0)
{
var catList = new List<ProductCategoryViewModel>();
foreach (var item in vm.SelectedCategoryIds) {
var cat = Context.ProductCategories.Where(c=>c.Id == item).FirstOrDefault();
catList.Add(Mapper.Map<ProductCategoryViewModel>(cat));
}
vm.ProductCategories = catList;
}
var model = Mapper.Map<Product>(vm);
model.CreatedDate = DateTime.Now;
model.IsDeleted = false;
Context.Products.Add(model);
Context.SaveChanges();
}
catch (Exception ex)
{
}
}
在这里,我想添加包含现有类别的新产品。 我该如何解决这个问题?
答案 0 :(得分:0)
根据您的实体,Product和ProductCategory类创建了多对多的关系。在ProductCategory中尝试此操作并检查
试试这个:
ExternalLoginCallback
答案 1 :(得分:0)
可能是
public void Add(ProductViewModel vm)
{
try {
var model = Mapper.Map<Product>(vm);
model.ProductCategories = new List<ProductCategory>();
//but this should be done by the Product ctor
if (vm.SelectedCategoryIds.Count() != 0) {
//var catList = new List<ProductCategoryViewModel>();
foreach (var item in vm.SelectedCategoryIds) {
var cat = Context.ProductCategories.Where(c=>c.Id == item).FirstOrDefault();
if ( cat != null )
model.ProductCategories.Add(cat);
//catList.Add(Mapper.Map<ProductCategoryViewModel>(cat));
}
//vm.ProductCategories = catList;
}
//var model = Mapper.Map<Product>(vm);
model.CreatedDate = DateTime.Now;
model.IsDeleted = false;
Context.Products.Add(model);
Context.SaveChanges();
}
catch (Exception ex)
{
}
}
请注意不要将foreach替换为单个查询
foreach (var item in Context.ProductCategories.
Where(c=> vm.SelectedCategoryIds.Contains(c.Id)))
{
model.ProductCategories.Add(item);
}
当然,正如Gert Arnold所建议的那样,有许多变体,例如使用Attach
....