开发者

code first - primary key constraint

开发者 https://www.devze.com 2023-02-03 00:10 出处:网络
I use code first(entity framework). when i call DbContext.SaveChanges(), I get a primary key constraint because here is already such a record. I want to override the record 开发者_Go百科if it already

I use code first(entity framework). when i call DbContext.SaveChanges(), I get a primary key constraint because here is already such a record. I want to override the record 开发者_Go百科if it already exists in the database. Which is the simplest way to do this. Checking each time I call savechanges for repeting primary keys is too hard in my project. Thanks


Unfortunately EF demands that you know if you are adding or modifing entity. So only ways are:

  • Keep this knowledge in your application and set proper EntityState in ObjectStateManager.
  • Load entity first. If exists modify its data, if doesn't create new entity and add it to context.
0

精彩评论

暂无评论...
验证码 换一张
取 消