我正在尝试将EF与插入存储过程一起使用,因为我无法直接访问该表。我的理解是,在代码中调用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();
}
存储过程:
ALTER PROCEDURE [dbo].[Insert]
@Title nvarchar (50),
@Description nvarchar (max)
AS
INSERT INTO [Product] (Title, Description) VALUES (@Title, @Description)
RETURN 0
自动生成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);
}
}