【发布时间】:2014-02-12 04:26:12
【问题描述】:
我从 formcollectionn 获取数据并将其存储到列表中我现在的问题是我的上下文。saveshange 没有将数据保存到地址数据库中是我的上下文在保存后为 0 吗?我真的不知道我的问题是因为先使用 sql构建我的实体框架?
public class AddressController : Controller
{
private readonly CustomersDBEntities context = new CustomersDBEntities();
//
// GET: /Address/
public ActionResult Index()
{
return View();
}
//
// GET: /Address/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
[HttpPost]
public ActionResult Create(Address address)
{
//Loop through the request.forms
var Addesslist = new List<Address>();
for (int i = 1; i <= Request.Form.Count; i++)
{
var street = Request.Form["street_0" + i + ""];
var city = Request.Form["city_0" + i + ""];
var postalCode = Request.Form["postalCode_0" + i + ""];
var province = Request.Form["province_0" + i + ""];
var personID = 1;
if (street != null && city != null && postalCode != null && province != null)
{
Addesslist.Add(new Address { Street = street, City = city, Province = province, PostalCode = postalCode, PersonID = personID });
Addesslist.ForEach(p => context.SaveChanges());
if (context.SaveChanges() == Addesslist.Count)
{
return RedirectToAction("Index");
}
else
{
//Redirect to an error page or
}
}
else
{
break;
}
}
return RedirectToAction("Index");
}
}
}
【问题讨论】:
-
您正在为
Addesslist中的每个项目保存一次。当您到达if语句中的context.SaveChanges()时,已经没有更多需要保存的更改了。 -
只是想问一下有没有批量插入线?
-
@rikitikitik 已删除 if 但我的数据库中仍然没有数据
-
你调试过你的代码吗?您是否 100% 确定正在创建 Address 对象?我注意到的另一件事是,如果在任何时候
(street != null && city != null && postalCode != null && province != null)为假,你就会打破循环。
标签: c# asp.net-mvc entity-framework asp.net-mvc-4