【发布时间】:2020-02-06 05:08:20
【问题描述】:
我有下面的这个方法,它将数据写入数据库中的两个表。我需要在 foreach 部分中将一个集合写入数据库。为什么 saveChanges 在循环的每次迭代中都不起作用,有更好的方法吗? 有两件事......第一:函数不返回任何东西....第二:数据库没有更新....当我从函数中删除 savechange() 时,它可以工作但没有改变值在数据库中。
if (_context.ProductPins.Where(a => a.ProductId == id && a.Status==false).Count() > 0)
{
var c = 0;
var ProductPins = _context.ProductPins.Where(a=>a.Status==false && a.ProductId == id);
foreach(var item in ProductPins)
{
ApplicationUser.Balance = ApplicationUser.Balance - product.BuyingPrice;
item.Equals(true);
_context.Statements.Add(new Statement
{
Amount = product.BuyingPrice,
RecordDate = DateTime.Now,
Destination = false,
FromApplicationUserId = _userManager.GetUserId(User),
//ToApplicationUserId = nu,
BalanceType = BalanceType.currentbalance,
});
_context.Update(ApplicationUser);
_context.Update(item);
_context.SaveChanges();
c++;
if (c > count)
{
break;
}
}
【问题讨论】:
-
你在使用实体框架吗?我知道 Dapper 允许您实际执行基于集合的插入,但看起来实体框架是正确的吗?
-
OP,请说明“不起作用”的含义。你有错误吗?例外?没有错误但数据没有保存?数据已保存但不正确?或者它是否符合规范,但您只是不喜欢代码结构?
-
@Greg 是的,我正在使用实体框架
-
@JohnWu 有两件事……第一:函数没有返回任何东西……第二:数据库不是最新的……当我从中删除 savechange()它具有的功能可以工作,但不会更改数据库中的值
-
@محمدالعاني - 如果您将 sql server 作为后端运行,您可以使用 sql profiler 检查吗? SaveChanges() 应该返回显示已保存记录数的 int。 (附带说明,您可以将 _context.ProductPins.Where(a => a.ProductId == id && a.Status==false).Count() > 0 更改为 _context.ProductPins.Any(a => a.ProductId == id && a.Status==false) 并将 _userManager.GetUserId(User) 置于循环之外)。
标签: c# asp.net entity-framework asp.net-mvc-3