如何使用组合主键在存储库模式工作单元 entity framework 中插入/删除记录
How to insert / Delete record in repository pattern unit of work entity framework with combined primary key
我有以下 table,只有两列带有组合主键
Table 名称: ProductByUser
第 1 列: ProductId (FK Ref. to Product Table)
第 2 列: UserId(FK Ref. to User Table)
附加信息: 在 edmx 中我也无法查看此 table 但它显示了产品之间的直接关系& 用户 Table.
我不知道如何删除或插入记录到此 table。因为我无法直接创建此 table 的对象。所以请指导我。
试试这个:
public class ProductByUser // Many to many table implemented as entity
{
public int ProductId { get; set; }
public int UserId { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<User> Users { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductByUser>()
.HasKey(c => new { c.ProductId , c.UserId });
modelBuilder.Entity<Product>()
.HasMany(c => c.ProductUsers)
.WithRequired()
.HasForeignKey(c => c.ProductId);
modelBuilder.Entity<User>()
.HasMany(c => c.ProductUsers)
.WithRequired()
.HasForeignKey(c => c.UserId);
}
终于找到出路了,希望对以后的人有所帮助,
void Insert(Product product, int intUserId)
{
_unitofWork.Db.Entry(product).Collection(i => i.Users).Load();
UserRepository userRepo = new UserRepository(_unitofWork);
product.Users.Add(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));
}
用于删除
product.Users.Remove(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));
我有以下 table,只有两列带有组合主键
Table 名称: ProductByUser
第 1 列: ProductId (FK Ref. to Product Table)
第 2 列: UserId(FK Ref. to User Table)
附加信息: 在 edmx 中我也无法查看此 table 但它显示了产品之间的直接关系& 用户 Table.
我不知道如何删除或插入记录到此 table。因为我无法直接创建此 table 的对象。所以请指导我。
试试这个:
public class ProductByUser // Many to many table implemented as entity
{
public int ProductId { get; set; }
public int UserId { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<User> Users { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductByUser>()
.HasKey(c => new { c.ProductId , c.UserId });
modelBuilder.Entity<Product>()
.HasMany(c => c.ProductUsers)
.WithRequired()
.HasForeignKey(c => c.ProductId);
modelBuilder.Entity<User>()
.HasMany(c => c.ProductUsers)
.WithRequired()
.HasForeignKey(c => c.UserId);
}
终于找到出路了,希望对以后的人有所帮助,
void Insert(Product product, int intUserId)
{
_unitofWork.Db.Entry(product).Collection(i => i.Users).Load();
UserRepository userRepo = new UserRepository(_unitofWork);
product.Users.Add(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));
}
用于删除
product.Users.Remove(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));