public class Person
{
[Required]
public int? KupaId { get; set; }
[ForeignKey("KupaId")]
public Kupa Kupa { get; set; }
public int? newKupaId { get; set; }
[ForeignKey("newKupaId")]
public Kupa NewKupa { get; set; }
}
public class Kupa
{
public int Id { get; set; }
[Index("Ix_uniqueId", IsUnique = true)]
public int ? uniqueId { get; set; }
}
public class MyController:Controller
{
public Json EditKupa(Expression<Func<Person,bool>> criteria )
{
using (IKupotRepository<Person> _IPersonRepository = new SQlRepository<Person>())
{
Person personToEdit=_IPersonRepository.SingleOrDefault(criteria,GetIncludeProperties());
> //Getting the new kupa obj from db
newKupa = GetKupa(UniqueId);
<//changing the unique property to null
personToEdit.Kupa.ToremId = null;
personToEdit.Kupa.State = State.Modified;
personToEdit.NewKupa = newKupa;
>//Assign the unique id property the value that was in the first Kupa
personToEdit.NewKupa.ToremId = 1;
personToEdit.newKupaId = newKupa.Id;
personToEdit.NewKupa.State = State.Modified;
_IPersonRepository.SaveChanges();
}
}
调用saveChanges()获取异常时:唯一键冲突,当查看sql profiler时,我可以看到EF 6为Kupa对象生成更新查询,但它会在更新前尝试更新NewKupa.uniqueId
Kupa.uniqueId
?
答案 0 :(得分:0)
假设您正在使用SQL Server作为数据库服务器,这是因为您在该列中允许NULL
值而NULL = NULL
为NULL
,因此如果您有多行{{1}在该列上,您将收到错误。
在SQL语句中实现这一点将是这样的:
NULL
但是,要在EF中执行此操作并不容易,但在此SO回答here中有一种解决方法。