好的,我正在尝试创建一个包含用户喜欢的项目的愿望清单,但是当我尝试将其添加到用户时,EF甚至没有尝试插入,什么也不做。
这是我最喜欢的产品型号
public class FavoriteProduct : BaseDeletableModel<int>
{
public string FashionNovaUserId { get; set; }
public FashionNovaUser FashionNovaUser { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
builder.Entity<FavoriteProduct>().HasKey(x => new { x.ProductId, x.FashionNovaUserId });
这是我的用户模型
public class FashionNovaUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<FavoriteProduct> FavoriteProducts { get; set; }
然后通过我的服务层,我试图将favoriteProduct添加到用户列表中
var favoriteProduct = new FavoriteProduct
{
ProductId = id,
FashionNovaUserId = user.Id
};
user.FavoriteProducts.Add(favoriteProduct);
this.db.SaveChanges();
当我这样做时,那里的数据库表没有更新,也没有任何新条目。
答案 0 :(得分:0)
由于FashionNovaUser
和Product
是多对多关系,因此,如果您想在连接表中添加FavoriteProduct
的记录,只需使用
var favoriteProduct = new FavoriteProduct
{
ProductId = id,
FashionNovaUserId = user.Id
};
this.db.Add(favoriteProduct);//or this.db.FavoriteProduct.Add(favoriteProduct)
this.db.SaveChanges();