实体框架5 - 已检测到关系'x'的劳力士的冲突变化

时间:2013-10-16 15:52:45

标签: c# entity-framework entity-framework-5

我有这个模型(动物模型):

    public int Id { get; set; }
    public int AnimalSpecieId { get; set; }
    public int AnimalBreedId { get; set; }
    public Nullable<int> ProtectorId { get; set; }
    public Nullable<int> OwnerId { get; set; }
    public string Name { get; set; }
    public virtual Owner Owner { get; set; }
    public virtual Protector Protector { get; set; }

保护者模型:

    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string CellPhone { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Animal> Animals { get; set; }

所有者模型:

    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string CellPhone { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Animal> Animals { get; set; }

第一次插入此模型时,如果

  

ProtectorID = 1

  

OwnerID = null

没关系,但是,我尝试更新此模型,改为:

  

OwnerID = 1

  

ProtectorID = null

我在标题中收到错误,有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:4)

我发现了这个问题,在阅读了这个msdn post后,我正在思考并发现发生了什么,在我的存储库中我将更新我的实体时,我正在伪造将所有相关实体设置为空。

旧代码:

var oldAnimal = context.Animals.Find(animal.Id);

if (oldAnimal != null)
{
    oldAnimal.AnimalBreed = context.AnimalBreeds.Find(animal.AnimalBreed.Id);
    oldAnimal.AnimalSpecie = context.AnimalSpecies.Find(animal.AnimalSpecie.Id);

    oldAnimal.OwnerId = animal.OwnerId;
    oldAnimal.ProtectorId = animal.ProtectorId;
    oldAnimal.Castrated = animal.Castrated;
    oldAnimal.DateBirth = animal.DateBirth;
    oldAnimal.Gender = animal.Gender;
    oldAnimal.Name = animal.Name;
    oldAnimal.UpdateDate = DateTime.Now;
    oldAnimal.Vaccinated = animal.Vaccinated;
    oldAnimal.Weight = animal.Weight;
}

context.SaveChanges();

return animal;

新代码:

var oldAnimal = context.Animals.Find(animal.Id);

if (oldAnimal != null)
{
    oldAnimal.AnimalBreed = context.AnimalBreeds.Find(animal.AnimalBreed.Id);
    oldAnimal.AnimalSpecie = context.AnimalSpecies.Find(animal.AnimalSpecie.Id);
    oldAnimal.Owner = null;
    oldAnimal.Protector = null;

    oldAnimal.OwnerId = animal.OwnerId;
    oldAnimal.ProtectorId = animal.ProtectorId;
    oldAnimal.Castrated = animal.Castrated;
    oldAnimal.DateBirth = animal.DateBirth;
    oldAnimal.Gender = animal.Gender;
    oldAnimal.Name = animal.Name;
    oldAnimal.UpdateDate = DateTime.Now;
    oldAnimal.Vaccinated = animal.Vaccinated;
    oldAnimal.Weight = animal.Weight;
}

context.SaveChanges();

return animal;

答案 1 :(得分:4)

我不同意上述答案。我不确定它是否永久解决了您的问题,因为该问题与空值赋值无关。实际原因与DBContext有关。当我们选择任何SaveChanges时,需要正确调度上下文,以便继续下一个SaveChanges将另一条记录插入到具有不同外键的同一项目上的DB中。您只需在“context.SaveChanges()

之后添加以下行
context.Entry(your object).State = System.Data.Entity.EntityState.Detached;

这将解决冲突。具有相同上下文的多次插入会导致冲突。

如果我的评论以任何方式批评你的回答,请道歉。