我正在构建一个具有多个层的 WCF 应用程序,并且在尝试将新对象添加到数据库时出现此异常。我将为您提供代码示例,请尝试在这里帮助我。错误在线scenaristBLL.Insert(s);
这是我尝试在ScenaristController
类中创建新的 Scenarist 对象的方法:
[HttpPost]
public ActionResult Create(ScenaristViewModel fvm, List<int> scenarijId)
{
if (fvm != null)
{
if (String.IsNullOrEmpty(fvm.Scenarist.NameSurname) == true)
{
TempData["ValidationErrorIme"] = "validation err1";
return RedirectToAction("Create");
}
if (fvm.Scenarist.DateOfBirth == null)
{
TempData["ValidationErrorGodina"] = "validation err2";
return RedirectToAction("Create");
}
Scenarist s = new Scenarist();
s.NameSurname = fvm.Scenarist.NameSurname;
s.DateOfBirth = fvm.Scenarist.DateOfBirth;
s.dateOfDeath = fvm.Scenarist.dateOfDeath;
scenaristBLL.Insert(s); // PROBLEM!
s = scenaristBLL.Fetch(s.Id);
foreach (int scenarij in scenarijId.Where(z => z != 0))
{
Scenarij scn = scenarijBLL.Fetch(scenarij);
if (scn == null)
{
return new HttpNotFoundResult("Nepostojeći scenaristId: " + scenarij.ToString());
}
scenarijBLL.AddToScenarist(scn, s);
}
}
return RedirectToAction("Index");
}
此外,这是它的 View 类:
<table>
<tr>
<td>Name and surname:</td>
<td>@Html.TextBoxFor(modelItem => Model.Scenarist.NameSurname) @TempData["ValidationError1"]</td>
</tr>
<tr>
<td>Date of birth:</td>
<td>@Html.TextBoxFor(modelItem => Model.Scenarist.DateOfBirth) @TempData["ValidationError2"]</td>
</tr>
<tr>
<td>Datum of Death:</td>
<td>@Html.TextBoxFor(modelItem => Model.Scenarist.DateOfDeath) @TempData["ValidationError3"]</td>
</tr>
</table>
我认为 DateOfBirth 和 DateOfDeath 可能是问题所在,因为它们是 DateTime 格式,我不确定如何从用户输入中获取 DateTime 格式。只是猜测,真的不确定。
此外,这里还有其他层...... BLL:
public void Insert(Scenarist scenarist)
{
string error;
if (scenarist.Validate(out error) == true)
{
string[] nameSurname = scenarist.NameSurname.Split(' ');
string name = nameSurname[0];
string surname = nameSurname[1];
dal.Insert(name, null, surname, scenarist.DateOfBirth, scenarist.DateOfDeath);
}
else
{
throw new ArgumentException("Validation error: " + error);
}
}
达尔:
public void Insert(string name, string middleName, string surname,
DateTime? dateOfB, DateTime? dateOfD)
{
using (RPPP111Entities ctx = new RPPP111Entities())
{
Scenarist scenarist = new Scenarist();
scenarist.Person.Name = name;
scenarist.Person.Middlename = middleName;
scenarist.Person.surname = surname;
scenarist.Person.DateOfB = dateOfB;
scenarist.Person.DateOfD = dateOfD;
ctx.Scenarist.Add(scenarist);
ctx.SaveChanges();
}
}