What I\'m trying to do is fairly simple. I have two classes:
public class TownRecord
{
public int Id { get; set; }
public string ShortName {
This doesn't work because you are using independent association. Relation between TownRecord
and TownRecordType
is not part of town record's entry so changing state to modified doesn't say anything about state of relation. That is the real meaning of "independent" - it has its own entry but for unknown reason it is hard to get it in DbContext API (EF 4.1). Proposed way is using Foreign key association instead of independent association. To change your association to foreign key you must do this:
public class TownRecord
{
public int Id { get; set; }
...
[ForeignKey("RecordType")]
public int RecordTypeId { get; set; }
public virtual TownRecordType RecordType { get; set; }
...
}
You will change your code to:
[HttpPost]
public ActionResult Edit(int id, TownRecord tr, FormCollection collection)
{
tr.RecordTypeId = Int32.Parse(collection["RecordType"]);
_ctx.TownRecords.Attach(tr);
_ctx.Entry(tr).State = EntityState.Modified;
_ctx.SaveChanges();
return RedirectToAction("List");
}
Actually the question with the same problem was asked 2 hours before you asked the question. I also tried to provide solution which works with independent association but I don't like it. The problem is that for independent association you need to have attached TownRecord
loaded its actual TownRecordType
and replace it with new TownRecordType
.