通用插入多对多 (Entity Framework)
Generic Insert many to many (Entity Framework)
我正在尝试使用按预期工作的通用方法插入新实体 (Product)。这个实体(产品)有另一个实体(供应商),当我尝试插入同一个产品和一个与之相关的新供应商(又名 Product.Suppliers.Add(NewSupplier))时,它会重新插入一个已经存在的产品(用seeder 方法)到数据库中......我知道它与供应商有关,因为当我不添加它并简单地插入产品并且不与同一供应商创建副本时。
这里有更多(简化的)信息:
产品实体:
public class Product : BaseEntity
{
public string ProductName { get; set; }
public virtual ICollection<Supplier> Suppliers { get; set; }
... others
}
供应商实体:
public class Supplier:BaseEntity
{
public string SupplierName { get; set; }
public virtual ICollection<Product> Products { get; set; }
... others
}
我有一个 ProductSupplier table,SupplierId 和 ProductId 使用 Fluent API。
在这种情况下,我仍然可以使用我的通用插入吗?如果可以,我做错了什么以及我做错了什么,为什么我从 DB 获得的 Supplier 被重新插入?
感谢大家的反馈!
亲切的问候
更新:
我认为这是因为我在执行 CRUD 操作时将上下文封装在 using 语句中。我遇到过 THIS POST
下周我会看一下,因为我必须实现其他功能。同时随意添加您的 2cents :)
更新 2
这是我的通用插入方法:
public static bool Insert<T>(T item) where T: class // here we specify that the <T> object is of type 'class'
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
ctx.Database.Log = (dbLog => logger.Debug(dbLog));
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
}
我尝试了几种方法,但到目前为止只有一种有效,所以我将继续使用这个方法,但请随时 post 你的(更好的)建议,这样我也许可以改进当前的解决方案。我做的很简单,我很确定一定有其他方法,但目前还不知道。每当我创建新实体时,在执行任何 insert/update 之前,我都会获取相关实体(如果它们存在)并将它们附加到要插入的实体,如果它们不存在,没关系,实体会为我插入它们。
希望这对任何人都有帮助。
亲切的问候
我正在尝试使用按预期工作的通用方法插入新实体 (Product)。这个实体(产品)有另一个实体(供应商),当我尝试插入同一个产品和一个与之相关的新供应商(又名 Product.Suppliers.Add(NewSupplier))时,它会重新插入一个已经存在的产品(用seeder 方法)到数据库中......我知道它与供应商有关,因为当我不添加它并简单地插入产品并且不与同一供应商创建副本时。
这里有更多(简化的)信息: 产品实体:
public class Product : BaseEntity
{
public string ProductName { get; set; }
public virtual ICollection<Supplier> Suppliers { get; set; }
... others
}
供应商实体:
public class Supplier:BaseEntity
{
public string SupplierName { get; set; }
public virtual ICollection<Product> Products { get; set; }
... others
}
我有一个 ProductSupplier table,SupplierId 和 ProductId 使用 Fluent API。 在这种情况下,我仍然可以使用我的通用插入吗?如果可以,我做错了什么以及我做错了什么,为什么我从 DB 获得的 Supplier 被重新插入?
感谢大家的反馈! 亲切的问候
更新: 我认为这是因为我在执行 CRUD 操作时将上下文封装在 using 语句中。我遇到过 THIS POST
下周我会看一下,因为我必须实现其他功能。同时随意添加您的 2cents :)
更新 2
这是我的通用插入方法:
public static bool Insert<T>(T item) where T: class // here we specify that the <T> object is of type 'class'
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
ctx.Database.Log = (dbLog => logger.Debug(dbLog));
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
}
我尝试了几种方法,但到目前为止只有一种有效,所以我将继续使用这个方法,但请随时 post 你的(更好的)建议,这样我也许可以改进当前的解决方案。我做的很简单,我很确定一定有其他方法,但目前还不知道。每当我创建新实体时,在执行任何 insert/update 之前,我都会获取相关实体(如果它们存在)并将它们附加到要插入的实体,如果它们不存在,没关系,实体会为我插入它们。
希望这对任何人都有帮助。 亲切的问候