[英]EF5 delete entity
How I can delete an entity using EF5? 如何使用EF5删除实体? I'm getting this error:
我收到此错误:
The object cannot be deleted because it was not found in the ObjectStateManager.
when I try to call .Remove on my DbSet. 当我尝试在我的DbSet上调用.Remove时。 After googling I tried that
谷歌搜索后,我尝试了
mycontext.Attach(entity)
mycontext.Remove(entity)
But in this way I get: 但是这样我得到:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
So, is it or not in ObjectStateManager?! 那么,是否在ObjectStateManager中? :)
:)
My entity is like that: 我的实体是这样的:
[Table("Words")]
public class Word : IWord
{
[Key, Required]
public int WordId { get; set; }
[Required, StringLength(50)]
public string Tag { get; set; }
//Foreign Key
public int VocabularyId { get; set; }
//Navigation
public virtual Vocabulary Vocabulary { get; set; }
public virtual Language Language { get; set; }
public virtual List<Translation> Translations { get; set; }
}
You can consider 2 scenario: 您可以考虑2种情况:
1. Connected scenario: you load the entity from database and mark it as deleted 1.已连接的场景:您从数据库中加载实体并将其标记为已删除
var word = ctx.Words.Where(a=>a.WordId == wordId).First();
ctx.DeleteObject(word);
ctx.SaveChanges();
2. Disconnected scenario: attach an existing entity and mark it as deleted 2.断开连接的场景:附加一个现有实体并将其标记为已删除
var word = new Word() { WordId = id };
ctx.Words.Attach(word);
ctx.DeleteObject(word);
ctx.SaveChanges();
The second approach will help you avoid un-necessary database round trip 第二种方法将帮助您避免不必要的数据库往返
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.