由于外键关系,Modelstate无效

时间:2012-11-01 15:36:45

标签: asp.net-mvc

由于ModelState无效,创建对象失败。任何帮助将不胜感激。简化模型如下:

public partial class Timerecord
{
    public int ID { get; set; }
    public int locationID { get; set; }
    public int teamID { get; set; }
    public int actionID { get; set; }
    public System.DateTime currentTime { get; set; }

    public virtual Location Location { get; set; }
    public virtual Action Action { get; set; }
}

由于错误,正确提供的Timerecord的创建失败: “从类型'System.String'到类型'Project.Models.Action'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。”} System.Exception {System.InvalidOperationException}

Timerecord的所有属性都很好,但Action和Location都是Null(这不是问题......因为外键是正确的)。我是否必须自己设置de外部对象然后重新评估模型,或者我必须提供构造函数Action(字符串)?

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Timerecord tm)
    {
        try
        {
            if (ModelState.IsValid)
            {
                db.Timings.Add(tm);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
                ...
            }
            ...

问题似乎是由Controller的Create方法引起的(简化):

    public ActionResult Create()
    {
        Timerecord tm = new Timerecord();
        LocationDBContext dbLoc = new LocationDBContext();
        ActionDBContext dbAct = new ActionDBContext();

        tm.currentTime = DateTime.Now;
        tm.locationID = 1;
        tm.actionID = 5;
        tm.Location = dbLoc.Location.Find(tm.locationID);
        /* THE PROBLEM: tm.Action = dbAct.Action.Find(tm.actionID); PROBLEM HERE */

        ViewData.Model = tm;
        return View();
    }

位置没有问题,行动确实.. 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

将Action重命名为Activity,一切正常! 猜猜绑定(...)搞砸了System.Action?!?没有其他解释。也许有人可以证实这种麻烦。