C# 实体框架4.1 RC(代码优先)-实体未通过关联更新
我想做的很简单。我有两门课:C# 实体框架4.1 RC(代码优先)-实体未通过关联更新,c#,entity-framework,code-first,entity-framework-4.1,C#,Entity Framework,Code First,Entity Framework 4.1,我想做的很简单。我有两门课: public class TownRecord { public int Id { get; set; } public string ShortName { get; set; } public string FileName { get; set; } public string tags { get; set; } public virtual TownRecordType
public class TownRecord
{
public int Id { get; set; }
public string ShortName { get; set; }
public string FileName { get; set; }
public string tags { get; set; }
public virtual TownRecordType RecordType { get; set; }
public DateTime? DateScanned { get; set; }
public DateTime? RecordDate { get; set; }
[StringLength(4000)]
public string Comments { get; set; }
public string UploadedBy { get; set; }
}
public class TownRecordType
{
public int Id { get; set; }
public string RecordType { get; set; }
public virtual ICollection<TownRecord> TownRecords {get; set; }
}
注意:为了清晰起见,我删除了错误处理
我见过类似的问题,但我不明白。这可能是一个非常愚蠢的新手错误,但我已经堆积如山,谷歌搜索了几个小时,结果一无所获。非常感谢您的帮助。这不起作用,因为您使用的是独立关联。
TownRecord
和TownRecordType
之间的关系不属于town record条目的一部分,因此将状态更改为modified不会说明任何关系状态。这就是“独立”的真正含义——它有自己的条目,但由于未知的原因,很难在DbContext API(EF 4.1)中获得它。提出的方法是使用外键关联代替独立关联。要将关联更改为外键,必须执行以下操作:
public class TownRecord
{
public int Id { get; set; }
...
[ForeignKey("RecordType")]
public int RecordTypeId { get; set; }
public virtual TownRecordType RecordType { get; set; }
...
}
您将代码更改为:
[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");
}
事实上,这个问题是在你提问前两个小时问的。我还试图提供解决方案,这与独立的协会工作,但我不喜欢它。问题是,对于独立关联,您需要附加
TownRecord
加载其实际TownRecordType
并将其替换为新的TownRecordType
,但是,它应该像OP一样工作,不是吗?我有一个User
类和一个public-virtual-IList-Suggestions{get;set;}
类,还有一个Suggestion
类和一个public-virtual-User-User{get;set;}
;它不需要显式标记FK关系,只需执行user.Suggestions.Add(suggestion)代码>…拉迪斯拉夫,谢谢。你的解决办法奏效了。由于一些验证,我仍然需要设置RecordType属性(tr.RecordType=new RecType),但它可以工作。很抱歉,我错过了你的其他答案,但非常感谢你的指导!可能重复的
[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");
}