In Alex James' Entity Framework tips articles, (which are excellent by the way) he talks about how to fake foreign key properties. This seems like exactly what I need, but for whatever reason I can't seem to pull it off when I'm updating. I have the following in update portion of my controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(candidates candidateToEdit)
{
string EduIDValue = candidateToEdit.education.ID.ToString();
if (!ModelState.IsValid)
return View();
try
{
var originalCandidate = (from c
in model.candidates
where c.ID == candidateToEdit.ID select c).FirstOrDefault();
//attempting it here
originalCandidate.educationReference.EntityKey = new System.Data.EntityKey("model.education", "ID", candidateToEdit.education.ID);
model.ApplyPropertyChanges(originalCandidate.EntityKey.EntitySetName, candidateToEdit);
model.SaveChanges();
return RedirectToAction("Index");
}
catch(Exception e)
{
Response.Write("Education ID Value " + EduIDValue + "<br /><br />Error: <br /><br />" + e);
return null;
//return View();
}
}
This fails and spits out the following:
System.ArgumentException: The member with identity 'model' does not exist in the metadata collection. Parameter name: identity at System.Data.Metadata.Edm.MetadataCollection1.GetValue(String identity, Boolean ignoreCase) at System.Data.Metadata.Edm.ReadOnlyMetadataCollection
1.GetValue(String identity, Boolean ignoreCase) at System.Data.Metadata.Edm.ItemCollection.GetEntityContainer(String name, Boolean ignoreCase) at System.Data.Metadata.Edm.ItemCollection.GetEntityContainer(String name) at System.Data.Metadata.Edm.MetadataWorkspace.GetEntityContainer(String name, DataSpace dataSpace) at System.Data.EntityKey.GetEntitySet(MetadataWorkspace metadataWorkspace) at System.Data.Objects.DataClasses.EntityReference.set_EntityKey(EntityKey value) at InternshipTest.Controllers.CandidatesController.Edit(candidates candidateToEdit) in C:\Documents and Settings\graham\My Documents\Visual Studio 2008\Projects\InternshipTest\InternshipTest\Controllers\CandidatesController.cs:line 84
Which doesn't make any sense to me, model is definitely the name of the EntitySet.
I figured it out, I did in fact have the EntitySet incorrect. I got around it by passing the following as the first argument when creating a new entity key:
originalCandidate.educationReference.EntityKey = new System.Data.EntityKey(originalCandidate.educationReference.EntityKey.EntityContainerName + "." + originalCandidate.educationReference.EntityKey.EntitySetName, "ID", candidateToEdit.education.ID);
Kinda nasty, but it works. Looking forward to the foreign key mess in EF being sorted out in .net 4.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With