更新唯一属性实体框架

本文关键字:框架 实体 属性 唯一 更新 | 更新日期: 2023-09-27 18:33:47

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 分析器时,我可以看到 EF 6 为两个 Kupa 对象生成更新查询,但它尝试在更新Kupa.uniqueId之前更新NewKupa.uniqueId

更新唯一属性实体框架

假设您使用 SQL Server 作为数据库服务器,发生这种情况是因为您允许该列中的NULL值并且NULL = NULL NULL因此,如果您有多行在该列上NULL,您将收到错误。

要在 SQL 语句中实现这一点,如下所示:

CREATE UNIQUE NONCLUSTERED INDEX Idx_UniqueId_NotNull
ON Kupa(uniqueId)
WHERE uniqueId IS NOT NULL;

但是,要在 EF 中执行此操作,没有简单的方法,但此处的 SO 答案中有一个解决方法。