[英]How to insert / Delete record in repository pattern unit of work entity framework with combined primary key
I have a following table with only two column with combined primary key我有一个只有两列和组合主键的下表
Table Name : ProductByUser表名: ProductByUser
Column 1 : ProductId (FK Ref. to Product Table)第 1 列: ProductId (FK 参考产品表)
Column 2 : UserId (FK Ref. to User Table)第 2 列:用户 ID(FK 参考用户表)
Additional Information: In edmx also I am not able to view this table but it show direct relationship between Product & User Table.附加信息:在 edmx 中,我也无法查看此表,但它显示了产品和用户表之间的直接关系。
I am not able to make out how to delete or Insert record into this table.我无法弄清楚如何在此表中删除或插入记录。 As I am not directly able to create an object of this table.因为我不能直接创建这个表的对象。 So kindly guide me on the same.所以请指导我。
Try this:尝试这个:
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);
}
Finally got the way out , Hope this will help some one in future,终于找到了出路,希望这对将来的人有所帮助,
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));
}
For deleting用于删除
product.Users.Remove(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.