我有这个模型
public class CPAppModel
{
[Key]
public string AppId { get; set; }
public string AppName { get; set; }
public string AppDescription { get; set; }
public virtual CPAppCategoryModel Category { get; set; }
public string Tags { get; set; }
}
我使用以下代码添加/更新条目
var db = new CheckpointApplicationContext();
if (int.Parse(AppModel.AppId) == 0) return;
if (!db.AppExist(AppModel))
{
db.Applications.Add(AppModel);
db.SaveChanges();
Message = "Record Added!";
}
else
{
var existingEntry = db.Applications.First(a => a.AppId == AppModel.AppId);
existingEntry.AppDescription = AppModel.AppDescription;
existingEntry.AppName = AppModel.AppName;
existingEntry.Category = AppModel.Category;
existingEntry.Tags = AppModel.Tags;
existingEntry.AppDescription = AppModel.AppDescription;
db.SaveChanges();
Message = "Record Updated!";
}
问题出在类别更新中。
场景是 - 我可能会为我的实体或其他(现有类别)获取新类别。 我认为,当使用延迟加载时,它会更新它"神奇地"一个人 - 事实并非如此。 我收到主键错误。
是否有更简单的方法为我的"整个实体"
实现添加/更新逻辑Attach对我不起作用
AddObject不是一个选项。
答案 0 :(得分:0)
我发现我忘了将类别添加为dbset 一旦我有了 - 附加开始工作。
db.Categories.Attach(AppModel.Category);
db.Applications.Attach(AppModel);
db.SaveChanges();