我在 MVC 中有一个多页面(多 View )表单,其结果将保存到单个数据库表中。
初始化表单第一页中的 linq 对象的代码片段。
public ActionResult MyForm()
{
// returns a Linq object stored in session
Application currentApp = Application.FromSession();
// if null, initialize the object and save to session
if (currentApp == null)
{
currentApp = new Application();
currentApp.SessionSave();
}
return View(currentApp);
}
这里是最后一个操作的示例代码片段,它从强类型模型更新一些数据,然后触发数据库保存。
[HttpPost]
public ActionResult MyForm3(Application app, FormCollection coll)
{
Application currentApp = Application.FromSession();
currentApp.Contact = app.Contact;
currentApp.AddFormToXml(coll);
currentApp.SessionSave();
_db.Applications.InsertOnSubmit(currentApp);
_db.SubmitChanges();
return RedirectToAction("Blah");
}
问题 我遇到的是 SubmitChanges 因错误而失败
Cannot insert the value NULL into column 'ApplicationData', table 'MyTable'; column does not allow nulls. INSERT fails. The statement has been terminated.
在这种情况下,ApplicationData 是 xml 类型的列,LINQ 将其解释为 XElement 对象。当我在 SubmitChanges() 设置断点并检查 app.ApplicationData 的值时,它显然已填充(非空),但我继续收到此错误。我唯一的想法是我误解了数据上下文的工作方式。不过,它似乎只有这一列有问题。我是否可能需要找出一种方法将 XElement 对象 (ApplicationData) 附加到我的事件数据上下文 (_db),如果是这样,我将如何去做?
最佳答案
查看生成并发送到服务器的实际 SQL。
启动 SQL Server Profiler(在 SQL Server Management Studio 的工具菜单上)并开始跟踪。运行您的应用程序,直到它崩溃。返回 SQL 事件探查器并查看 SQL 查询。从 SQL 端看问题有时可以很容易地发现错误,例如确定您是否在进行多次插入而不是一次插入。
关于c# - ASP.NET MVC 3 - Linq to SQL 对象存储在 session 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892303/