for*_*tme 16 c# entity-framework
我正在尝试更新记录,之后我收到此错误消息 context.SaveChanges();
属性"name"是对象的关键信息的一部分,不能修改.
以下是更新功能的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的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; }
Run Code Online (Sandbox Code Playgroud)
我搜索了类似的问题,但找不到任何有效的解决方案.
nvu*_*ono 35
请参阅yildizm85对此问题的回答:实体框架不在没有标识列的表上工作
"实体框架需要主键从数据库生成模型.如果表上没有主键,它将只选择不可为空的列作为连接主键,实体将被读取/仅."
查看EAT_SourceNames对象时,似乎没有主键字段,因此实体框架使用列'name'作为组合键的一部分,这意味着它是只读的.
解决方案是添加主键字段EAT_SourceNames,然后您的"名称"字段将不再是主键的一部分.
我今天也发生了同样的事.我用旧记录的ID设置新实体的ID,错误消失了.
//This checks whether there's a record with same specific data.
var kayitVarMi = _db.Sorgu.FirstOrDefault(a => a.Serial == sorgu.Serial);
if (kayitVarMi != null) // If there's
{
sorgu.Id = kayitVarMi.Id; //This one does the trick
_db.Entry(kayitVarMi).CurrentValues.SetValues(sorgu);
}
else // If not
{
_db.Sorgu.Add(sorgu);
}
// This whole block is in a transaction scope so I just check recordability.
if (_db.SaveChanges() > 0)
{
_sorguKaydedildiMi = true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39228 次 |
| 最近记录: |