기존 데이터베이스 항목에 대한 업데이트를 저장하려고하는데 오류가 발생합니다.
동일한 유형의 다른 엔티티에 이미 동일한 기본 키 값이 있으므로 'FFInfo.DAL.Location'유형의 엔티티를 첨부하지 못했습니다. 이는 'Attach'메서드를 사용하거나 그래프의 항목에 충돌하는 키 값이있는 경우 항목의 상태를 '변경되지 않음'또는 '수정 됨'으로 설정할 때 발생할 수 있습니다. 일부 항목이 새 항목이고 아직 데이터베이스 생성 키 값을받지 않았기 때문일 수 있습니다. 이 경우 'Add'메소드 또는 'Added'항목 상태를 사용하여 그래프를 추적 한 다음 새 항목이 아닌 항목의 상태를 'Unchanged'또는 'Modified'로 적절하게 설정합니다.
이것은 내 컨트롤러의 코드입니다. 내가 사용하는 저장 방법은 문제없이 데이터를 업데이트하기 위해 몇 가지 다른 영역에서 사용하는 것과 동일합니다.
[HttpPost, ValidateAntiForgeryToken]
public ActionResult EditLocation(AddEditLocationVM model, HttpPostedFileBase MapFile)
{
try
{
using (var db = new GeographyContext())
{
model.Sections = new SelectList(db.Sections.Where(s => s.ID > 1).OrderBy(s => s.Title), "ID", "Title").ToList();
model.GeographyTypes = new SelectList(db.GeographyTypes.Where(gt => gt.SectionID == model.Section).OrderBy(gt => gt.Name), "ID", "Name").ToList();
model.ParentLocations = new SelectList(db.Locations.Where(l => l.SectionID == model.Section).OrderBy(l => l.Name), "ID", "Name").ToList();
if (MapFile != null)
{
if (FileHelper.IsNotValidImage(MapFile))
{
ModelState.AddModelError("Invaalid File Type", "Images must be JPG, GIF, or PNG files.");
}
}
if (ModelState.IsValid)
{
if (MapFile != null)
{
var SectionRoute = db.Sections.Where(s => s.ID == model.Section).Select(s => s.Route).First();
model.MapFileID = FileHelper.UploadFile("Images/" + SectionRoute + "/Maps/" + MapFile.FileName.ToList(), "site", MapFile);
}
if (model.ParentLocation == 0)
{
model.ParentLocation = null;
}
var UpdatedLocation = new Location()
{
Description = model.Description,
GeographyTypeID = model.GeographyType,
ID = model.ID,
MapFileID = model.MapFileID,
Name = model.Name,
ParentLocationID = model.ParentLocation,
SectionID = model.Section
};
db.Entry(UpdatedLocation).State = EntityState.Modified;
db.SaveChanges();
ViewBag.Results = "Location information updated.";
}
return View(model);
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
model.Sections = Enumerable.Empty<SelectListItem>();
ViewBag.Results = "Error updating location informaiton, please try again later.";
return View(model);
}
}
이것은 내 위치 엔터티 코드입니다.
public class Location
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required, Index("IX_Location", 1, IsUnique = true)]
public string Name { get; set; }
[Index("IX_Location", 2, IsUnique = true)]
public Int16 SectionID { get; set; }
[Column(TypeName = "varchar(MAX)")]
public string Description { get; set; }
public Int16 GeographyTypeID { get; set; }
public int? MapFileID { get; set; }
public int? ParentLocationID { get; set; }
[ForeignKey("SectionID")]
public Section Section { get; set; }
[ForeignKey("GeographyTypeID")]
public GeographyType GeographyType { get; set; }
[ForeignKey("MapFileID")]
public File Map { get; set; }
[ForeignKey("ParentLocationID")]
public Location ParentLocation { get; set; }
public ICollection<LocationTransitionPoint> TransitionPoints { get; set; }
}
이와 같이 더 복잡한 엔티티를 업데이트하려고 시도하는 것은 이번이 처음이지만 웹에서 찾은 내용에서 잘못된 것을 볼 수 없습니다.
Entity Framework의 메모리에는 동일한 기본 키를 가진 두 개의 엔터티 (동일한 유형)가있을 수 없습니다.
문제는
model.ParentLocations = new SelectList(db.Locations.Where(l => l.SectionID == model.Section).OrderBy(l => l.Name), "ID", "Name").ToList();
위의 줄을 당신은 어떻게 든로드 한 Location
있는 자사의 ID
IS를model.ID
그런 다음
var UpdatedLocation = new Location()
{
Description = model.Description,
GeographyTypeID = model.GeographyType,
ID = model.ID,
MapFileID = model.MapFileID,
Name = model.Name,
ParentLocationID = model.ParentLocation,
SectionID = model.Section
};
db.Entry(UpdatedLocation).State = EntityState.Modified;
새 항목을 만들고 Location
컨텍스트에 연결하려고하지만 (상태를 수정 됨으로 설정하여) Location
정확한 기본 키가있는 다른 엔터티 UpdatedLocation
를 메모리 어딘가에로드했으며 이로 인해 예외가 발생합니다.
위치를 가져 와서 로프티를 변경하십시오.
var UpdateLocation = db.Locations.First(l => l.ID == model.ID);
// var UpdateLocation = db.Locations.Find(model.ID); maybe a better option
UpdatedLocation.Description = model.Description;
UpdatedLocation.GeographyTypeID = model.GeographyType;
UpdatedLocation.MapFileID = model.MapFileID;
UpdatedLocation.Name = model.Name;
UpdatedLocation.ParentLocationID = model.ParentLocation;
UpdatedLocation.SectionID = model.Section;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다