Entity Framework 5를 사용하여 N-Layer를 사용하는 ASP.NET WebForms 프로젝트가 있습니다. Cliente와 Banda의 두 엔티티가 있습니다. 한 Cliente 많은 반다의 가질 수 있으며, 하나의 반다 많은 Cliente 년대 탈취 층에서EF5에서 many to many 관계를 업데이트 할 때 오류가 발생했습니다
이 코드가있을 수 있습니다
public void Update(Cliente cliente)
{
using (MegaStudioEntities contexto = new MegaStudioEntities())
{
if (contexto.Entry(cliente).State == EntityState.Detached)
contexto.Entry(cliente).State = EntityState.Modified;
//Delete existing relations
var qBandas = from qb in contexto.Bandas.Where(b => b.Clientes.Any(c => c.IdCliente == cliente.IdCliente))
select qb;
foreach (Banda b in qBandas.ToList())
((IObjectContextAdapter)contexto).ObjectContext.ObjectStateManager.ChangeRelationshipState(cliente, b, c => c.Bandas, EntityState.Deleted);
contexto.SaveChanges();
//Adding new relations
foreach (Banda banda in cliente.Bandas)
{
contexto.Bandas.Attach(banda);
((IObjectContextAdapter)contexto).ObjectContext.ObjectStateManager.ChangeRelationshipState(cliente, banda, c => c.Bandas, EntityState.Added);
}
cliente.TipoCliente = contexto.TipoClientes.Find(cliente.IdTipoCliente);
cliente.FechaModificacion = System.DateTime.Now;
Encriptar(cliente);
contexto.SaveChanges();
}
}
내가 Update 메서드를 호출 처음으로, 성공적으로 실행되지만 두 번째
"동일한 키를 가진 객체가 ObjectStateManager에 이미 존재하며 ObjectStateManager는 동일한 키를 가진 여러 객체를 추적 할 수 없습니다."
내가 닫을 것을 잊었을 때? 이것은 EF5에서 많은 관계를 많은 관계로 업데이트하는 올바른 방법입니까?
미리 감사드립니다.
마틴
UPDATE 1 :
마지막으로 내 코드가 같다 :
public void Update(Cliente cliente)
{
using (MegaStudioEntities contexto = new MegaStudioEntities())
{
Cliente savedClient = contexto.Clientes.Find(cliente.IdCliente);
foreach (var banda in savedClient.Bandas.ToList())
{
savedClient.Bandas.Remove(contexto.Bandas.Find(banda.IdBanda));
}
foreach (var banda in cliente.Bandas)
{
savedClient.Bandas.Add(contexto.Bandas.Find(banda.IdBanda));
}
contexto.Entry(savedClient).CurrentValues.SetValues(cliente);
contexto.SaveChanges();
}
}
감사 거트 아놀드!
오류가 발생하는 줄은 무엇입니까? –
wery 중요한 줄'savedClient.Bandas.Remove (contexto.Bandas.Find (banda.IdBanda))' – Kuncevic