我正在使用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错误
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”):
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);
哪个也行不通。我觉得我在这里缺少一些基本的东西。有任何想法吗?
谢谢,史蒂夫
答案 0 :(得分:0)
经过更多的工作,我找到了一个解决方法。基本上,我不得不忽略验证错误,然后手动删除现有的ContactTypes,然后添加用户选择的那些。我确实尝试为Contact.ContactTypes属性构建自定义验证器,但始终将ContactType对象传递给该方法;我从未见过字符串数组。不可否认,这是我建立的第一个自定义验证器,所以也许我错过了一些东西。
无论如何,这是我最终得到的编辑方法:
//
// 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);
}