我正在尝试更新一个记录,并在context.SaveChanges();之后得到这个错误信息.
The property ‘name’ is part of the object’s key information and cannot be modified.
if (context.EAT_SourceNames.Any(e => e.name == newSourceName)) { MessageBox.Show("Name already exists in the Database"); } else { var nameToUpdate = context.EAT_SourceNames.SingleOrDefault(e => e.name == sourceName.name); if (nameToUpdate != null) { nameToUpdate.name = newSourceName; context.SaveChanges(); RefreshDGVs(); } }
我的SourceNames类看起来像下面这样:
public EAT_SourceNames() { this.EAT_Sources = new ObservableListSource<EAT_Sources>(); } public string name { get; set; } public string version_id { get; set; } public string allocation_name { get; set; }@H_301_16@
解决方法
看到yildizm85的答案到这个问题:
entity framework not working on table without identity column
“实体框架”需要一个主键从数据库中生成一个模型,如果一个表上没有主键,它将简单地选择不可为空的列作为连接的主键,并且实体将被读/只.
看看您的EAT_SourceNames对象,它看起来没有主键字段,所以Entity Framework使用列’name’作为复合键的一部分,这意味着它是只读的.
解决方案是将主键字段添加到EAT_SourceNames,然后您的“名称”字段将不再是主键的一部分.
@H_301_16@ @H_301_16@