Entity framework 在实体框架中调用SaveChanges之前更新数据库
我试图将EF与insert存储过程一起使用,因为我无法直接访问表。我的理解是,在代码中调用Entity framework 在实体框架中调用SaveChanges之前更新数据库,entity-framework,stored-procedures,Entity Framework,Stored Procedures,我试图将EF与insert存储过程一起使用,因为我无法直接访问表。我的理解是,在代码中调用SaveChanges()之前,不应该更新数据库,但插入时数据库会更新。在本例中,进行了4次数据库调用 我如何做到只有一个数据库调用并更新多个记录 这可以归类为数据库优先EF?存储过程以正常方式作为函数导入edmx 代码示例: public ActionResult Index() { List<Product> products = new List<Product>
SaveChanges()
之前,不应该更新数据库,但插入时数据库会更新。在本例中,进行了4次数据库调用
我如何做到只有一个数据库调用并更新多个记录
这可以归类为数据库优先EF?存储过程以正常方式作为函数导入edmx
代码示例:
public ActionResult Index()
{
List<Product> products = new List<Product> {
new Product() { Title = "coca cola", Description = "good"},
new Product() { Title = "apple", Description = "fruit"},
new Product() { Title = "orange", Description = "fruit"},
new Product() { Title = "banana", Description = "my favourite"}
};
EFwithSPtest context = new EFwithSPtest();
foreach(var p in products)
{
context.Insert(p.Title, p.Description);
}
context.SaveChanges();
return View();
}
自动生成的DbContext
类:
public partial class EFwithSPtest : DbContext
{
public EFwithSPtest()
: base("name=Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual int Insert(string title, string description)
{
var titleParameter = title != null ?
new ObjectParameter("Title", title) :
new ObjectParameter("Title", typeof(string));
var descriptionParameter = description != null ?
new ObjectParameter("Description", description) :
new ObjectParameter("Description", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("Insert", titleParameter, descriptionParameter);
}
}
可能的副本。这正是你的问题
ObjectContext.ExecuteFunction本身有自己的事务。只需在此处添加以下内容:最好使用
块将上下文包装在中。不会改变或解决你正在处理的问题,但这是一个好习惯。谢谢。Gert唯一的技巧是将调用封装在一个TransactionScope中。打电话给SaveChanges根本不需要。非常感谢Gert。。我现在开始工作了D
public partial class EFwithSPtest : DbContext
{
public EFwithSPtest()
: base("name=Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual int Insert(string title, string description)
{
var titleParameter = title != null ?
new ObjectParameter("Title", title) :
new ObjectParameter("Title", typeof(string));
var descriptionParameter = description != null ?
new ObjectParameter("Description", description) :
new ObjectParameter("Description", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("Insert", titleParameter, descriptionParameter);
}
}