EF Core-无法使用复合键添加对象

时间:2019-11-11 16:10:01

标签: entity-framework asp.net-core .net-core asp.net-core-mvc entity-framework-core

好的,我正在尝试创建一个包含用户喜欢的项目的愿望清单,但是当我尝试将其添加到用户时,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();

当我这样做时,那里的数据库表没有更新,也没有任何新条目。

1 个答案:

答案 0 :(得分:0)

由于FashionNovaUserProduct是多对多关系,因此,如果您想在连接表中添加FavoriteProduct的记录,只需使用

var favoriteProduct = new FavoriteProduct
        {
            ProductId = id,
            FashionNovaUserId = user.Id
        };

this.db.Add(favoriteProduct);//or this.db.FavoriteProduct.Add(favoriteProduct)
this.db.SaveChanges();