为什么实体框架仅保存列表的最后一项? [英] why does entity framework saves only the last item of a list?
问题描述
我有2个具有一对多关系的对象.我试图在使用通用存储库的同时将多个具有相同ProductId的ProductImage添加到数据库中.
I have 2 objects with one to many relation. I'm trying to add multiple ProductImages with the same ProductId to the data base, while using a generic repository.
我尝试使用dbSet.AddRange将ProductImage列表保存到存储库中.之后,我用context.SaveChanges();保存了它.我也尝试过遍历ProductImage列表,并使用dbSet.Add添加每个项目,而不是context.SaveChanges().
I have tried saving a list of ProductImage to a repository with dbSet.AddRange . after that i saved it with context.SaveChanges(); i have also tried looping trough the list of ProductImage and adding each item with dbSet.Add .and than context.SaveChanges() .
存储库方法:
public virtual void Add(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void AddRange(List<TEntity> entityList)
{
dbSet.AddRange(entityList);
}
public void Save()
{
context.SaveChanges();
}
结果是保存到数据库的对象始终是最后一个-但我想保存所有对象.
the result is the object saved to the data base is always the last one - but i want to save all of them.
修改添加对象的方法:
private Task<int> InsertProductImagesToDB(List<ProductImageVM> productImages, int productId, List<IFormFile> imageFiles)
{
if (productImages?.Any()==true)
{
List<ProductImage> dbEntitys = new List<ProductImage>();
for(int i=0; i< productImages.Count; i++)
{
ProductImage p = productImages[i].ConvertToProductImageEntity(imageFiles[i], productId);
dbEntitys.Add(p);
}
ImagesRepository.AddRange(dbEntitys);
ImagesRepository.Save();
return Task.FromResult(dbEntitys.First().Id);//return first productImage as the main image
}
return Task.FromResult(-1);
}
正如您在注释中提到的那样-对象构造函数不在循环之外.调试时,我可以看到dbEntitys列表包含2个具有不同值的项目.
as some of you mentioned in the comments - the object constructor is not outside the loop. while debugging i can see the dbEntitys list contains 2 items with defferent values.
图像:保存更改后的数据库表:
image of the dbset after adding the objects before saving changes: db table after changes were saved:
推荐答案
将我的头撞在墙上几天后-我终于找到了解决方案.
after banging my head against the wall for a few days - i finally got the solution.
问题出在我的ProductImage实体中,如下所示:
the problem was in my ProductImage Entity which looked like this:
public class ProductImage : ImageProp, DBEntity
{
[Column("Name", TypeName = "nvarchar(200)"), Required, Display(Name = "שם"), MaxLength(200)]
public string Name { get; set; }
public Product Product { get; set; }
[Required]
public int ProductId { get; set; }
}
所以问题出在这一行:
public Product Product { get; set; }
显然为数据库表中的ProductId字段创建了唯一键.当我尝试添加具有相同ProductId的多个ProductImage时,出现了一个SQL异常,提示我无法为ProductId插入重复值.
which apparently created a unique key for ProductId field in the data base table. when i tried to add multiple ProductImages with the same ProductId, i got an sql exception that said i cannot insert duplicate value for ProductId.
删除此行解决了问题.
这篇关于为什么实体框架仅保存列表的最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!