0

我正在使用 EF4 CTP5 并且无法将记录保存回数据库。我有 Contact 和 ContactType 实体。正如帖子标题所述,我在表格之间设置了多对多导航属性。

问题在于验证 ContactType 值。ModelState.IsValid 为 false,因为它无法将从表单传回的值(ContactType id 的字符串数组转换为 ContactType 对象。

POCO的

public partial class Contact
{
    public Contact()
    {            
        this.ContactTypes = new HashSet<ContactType>();
    }

    // Primitive properties
    public int ContactId { get; set; }
    public string ContactName { get; set; }

    // Navigation properties
    public virtual ICollection<ContactType> ContactTypes { get; set; }
}

public partial class ContactType
{
    public ContactType()
    {
        this.Contacts = new HashSet<Contact>();
    }

    // Primitive properties
    public int ContactTypeId { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual ICollection<Contact> Contacts { get; set; }
}

控制器

//
// GET: /Contact/Edit/5
public virtual ActionResult Edit(int id)
{
    Contact contact = context.Contacts.Include(c => c.ContactTypes).Single(x => x.ContactId == id);
    ViewData["ContactTypesAll"] = GetTypesList();
    return View(contact);
}

//
// POST: /Contact/Edit/5
[HttpPost]
public virtual ActionResult Edit(Contact contact)
{
    if (ModelState.IsValid)
    {
        context.Entry(contact).State = EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("Index");
    }   
    ViewData["ContactTypesAll"] = GetTypesList();
    return View(contact);
}

看法

<div class="field-block">
    @Html.LabelFor(model => model.ContactId)
    @Html.EditorFor(model => model.ContactId, new { fieldName = "ContactId" })
    @Html.ValidationMessageFor(model => model.ContactId)
</div>
<div class="field-block">
    @Html.LabelFor(model => model.OrganizationNameInternal)
    @Html.EditorFor(model => model.OrganizationNameInternal)
    @Html.ValidationMessageFor(model => model.OrganizationNameInternal)
</div>
<div class="field-block">
    @Html.LabelFor(model => model.ContactTypes)
    @Html.ListBoxFor(modelContactType, 
            new MultiSelectList((IEnumerable<TDAMISObjects.ContactType>)ViewData["ContactTypesAll"],
                "ContactTypeId",
                "Name",
                Model.ContactTypes))
    @Html.ValidationMessageFor(model => model.ContactTypes)
</div>

模型状态错误

ModelState.Values.ElementAt(2).Value
{System.Web.Mvc.ValueProviderResult}
    AttemptedValue: "5"
    Culture: {en-US}
    RawValue: {string[1]}

ModelState.Values.ElementAt(2).Errors[0]
{System.Web.Mvc.ModelError}
    ErrorMessage: ""
    Exception: {"The parameter conversion from type 'System.String' to type 'ProjectObjects.ContactType' failed because no type converter can convert between these types."}

所以看起来很清楚问题是什么,但我似乎找不到解决方案。我尝试手动将 ContactType id 转换为 ContactType 对象,并将它们添加到传递给 Edit 函数的 Contact 对象(称为“联系人”):

contact.ContactTypes.Clear();
string[] ids = this.HttpContext.Request.Form["ContactTypes"].Split(',');
for(int i = 0; i< ids.Length; i++)
{
    int x = Convert.ToInt32(ids[i]);
    ContactType selectedType = context.ContactTypes.Single(t => t.ContactTypeId == x);
    contact.ContactTypes.Add(selectedType);
}

但错误仍然存​​在。我也试过打电话

context.ChangeTracker.DetectChanges();

但这并没有奏效。我还手动为不会验证的值设置 ValueProviderResult,使用

ModelState.SetModelValue("ContactTypes", val);

这也没有奏效。我觉得我在这里缺少一些基本的东西。有任何想法吗?

谢谢,史蒂夫

4

1 回答 1

0

好吧,经过更多的工作,我找到了解决方法。基本上,我不得不忽略验证错误,然后手动删除现有的 ContactTypes,然后添加用户选择的那些。我确实尝试为 Contact.ContactTypes 属性构建自定义验证器,但始终将 ContactType 对象传递给该方法;我从未见过字符串数组。诚然,这是我构建的第一个自定义验证器,所以也许我遗漏了一些东西。

无论如何,这是我最终得到的 Edit 方法:

//
// POST: /Contact/Edit/5
[HttpPost]
public virtual ActionResult Edit(Contact contact)
{
    // clear up ModelState.IsValid for contact type
    ModelState.Remove("ContactTypes");

    if(ModelState.IsValid)
    {
        // remove all contact types for contact
        Contact dummy = context.Contacts.Single(c => c.ContactId == contact.ContactId);
        if(dummy.ContactTypes.Count > 0)
        {
            dummy.ContactTypes.Clear();
            context.Entry(dummy).State = EntityState.Modified;
            context.SaveChanges();
        }
        context.Detach(dummy);
        context.Contacts.Attach(contact);

        // add currently selected contact types, then save
        string[] ids = this.HttpContext.Request.Form["ContactTypes"].Split(',');
        for(int i = 0; i< ids.Length; i++)
        {
            int x = Convert.ToInt32(ids[i]);
            ContactType selectedType = context.ContactTypes.Single(t => t.ContactTypeId == x);
            contact.ContactTypes.Add(selectedType);                    
        }
        context.Entry(contact).State = EntityState.Modified;
        context.SaveChanges();

        ViewBag.Message = "Save was successful.";
    }

    ViewData["ContactTypes"] = contact.ContactTypes.Select(t => t.ContactTypeId);
    ViewData["ContactTypesAll"] = GetTypesList();            
    return View(contact);
}

我还必须在我的 DBContext 类中添加一个 Detach 方法(在 CTP 5 中这没有公开):

public void Detach(object entity) 
{
    ((System.Data.Entity.Infrastructure.IObjectContextAdapter)this).ObjectContext.Detach(entity);
}
于 2011-02-16T15:04:58.100 回答