0
的衝突期間更新收到錯誤:EF。更新。唯一鍵約束
Violation of UNIQUE KEY constraint 'IX_UniqueClientRequest'. Cannot insert duplicate key in object 'dbo.ClientRequest'. The duplicate key value is (0067f654-a06a-47c1-a13d-d5f35530c11b, -1).
該語句已終止。
這是我使用的代碼:
public class ClientRequestData
{
public Guid Id { get; set; }
public ClientData Client { get; set; }
}
public class ClientRequestDataConfig : EntityTypeConfiguration<ClientRequestData>
{
public ClientRequestDataConfig()
{
ToTable("ClientRequest");
HasRequired(r => r.Client)
.WithMany(c => c.ClientRequests)
.Map(m => m.MapKey("IdClient"))
.WillCascadeOnDelete(false);
}
}
public void Save(ClientRequestData request)
{
using (DbContext context = new DbContext())
{
request.Client = context.Clients.FirstOrDefault(c => c.Id == request.Client.Id);
//Insert
if (request.Id == Guid.Empty)
{
request.Id = Guid.NewGuid();
context.ClientRequests.Add(request);
}
//Update
else
{
ClientRequestData dbRequest = context.ClientRequests.FirstOrDefault(cr => cr.Id == request.Id);
dbRequest.Client = request.Client;
}
context.SaveChanges();
}
}
如何更改客戶端實體狀態,所以它refernce僅更新,而不是試圖肌酸新的客戶端?
爲什麼實體框架重新插入現有的對象到我的數據庫? msdn.microsoft.com/en-us/magazine/dn166926.aspx – Colin