我对此有点困惑,我正在实施一个愿望清单,其中多个用户可以将相同的实体(产品)添加到他们的列表中。我扩展了身份用户类并添加了一个ICollection<Product>
但我似乎无法弄清楚多个用户如何在外键方面引用同一产品,因为每当用户将产品添加到他们的愿望清单时,它就会从以前的用户中删除外键现在引用新用户。显然我的逻辑有缺陷,我误解了应该如何定义这种关系,你能指出我正确的方向吗?
这是产品实体
public class Product
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int ProductId { get; set; }
public string ProductName { get; set; }
public virtual ProductType ProductType { get; set; }
[ForeignKey("Category")]
public int SubcategoryFK { get; set; }
public virtual SubCategory Category { get; set; }
public decimal Price { get; set; }
public int NumberOfItems { get; set; }
public string ImageUrl { get; set; }
public string IsInStock { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
[ForeignKey("SalesUser")]
public string SalesUserFK { get; set; }
public virtual ApplicationUser SalesUser { get; set; }
并且关系是这样配置的
modelBuilder.Entity<ApplicationUser>()
.HasMany(a => a.Products)
.WithOne(p => p.SalesUser).HasForeignKey(z => z.SalesUserFK).OnDelete(DeleteBehavior.ClientSetNull);
作为箕评论,关系Product
和User
是许多一对多。在 EF Core 中,尚不支持没有实体类来表示连接表的多对多关系。但是,您可以通过为连接表包含一个实体类并映射两个单独的一对多关系来表示多对多关系。
public class Product
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int ProductId { get; set; }
public string ProductName { get; set; }
public virtual ProductType ProductType { get; set; }
[ForeignKey("Category")]
public int SubcategoryFK { get; set; }
public virtual SubCategory Category { get; set; }
public decimal Price { get; set; }
public int NumberOfItems { get; set; }
public string ImageUrl { get; set; }
public string IsInStock { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public List<UserProduct> UserProducts { get; set; }
}
public class ApplicationUser:IdentityUser
{
public List<UserProduct> UserProducts { get; set; }
}
public class UserProduct
{
public int ProductId { get; set; }
public Product Product { get; set; }
public Guid ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
数据库上下文:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserProduct>()
.HasKey(up => new { up.ProductId, up.ApplicationUserId });
modelBuilder.Entity<UserProduct>()
.HasOne(up => up.Product)
.WithMany(p => p.UserProducts)
.HasForeignKey(up => up.ProductId);
modelBuilder.Entity<UserProduct>()
.HasOne(up => up.ApplicationUser)
.WithMany(au => au.UserProducts)
.HasForeignKey(up => up.ApplicationUserId);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句