我在從Entity框架中的模型集合中嘗試項目時遇到此錯誤。我得到以下錯誤:附加實體中的錯誤
Attaching an entity of type '' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate
請能有人幫忙我堅持 這裏是我的代碼:
public class Attendees
{
[Key]
public int AttendeesId { get; set; }
public ICollection<Programme> programmes { get; set; }
public ICollection<Presentations> presentations { get; set; }
public ICollection<Abstracts> abstracts { get; set; }
[Required]
public bool IsKeynoteSpeaker { get; set; }
}
public class Programme
{
[Key]
public int ProgrammeId { get; set; }
[Required, MaxLength(256,
ErrorMessage = "The length of the field is more than expected")]
public string Title { get; set; }
public ICollection<Attendees> presenters { get; set; }
public ICollection<Attendees> chairpersons { get; set; }
public ProgrammeType programmeType { get; set; }
public ConferenceDay Daynumber { get; set; }
}
public void RemovePresenterFromProgramme(Programme programme,Attendees attendees)
{
var context = _programmeRepository.GetGenericRepository.GetDbContext as ConferenceDbContext;
context.Entry(programme).State = System.Data.Entity.EntityState.Modified; // get the error here
var attendee = programme.presenters
.Where(c => c.AttendeesId == attendees.AttendeesId).SingleOrDefault();
programme.presenters.Remove(attendee);
context.SaveChanges();
}
感謝帕特爾的迴應。但是,我應用了更改,在附加代碼中引發了同樣的錯誤。 –
@ user3314516,從哪裏加載了'(Program program)'?如果'programme'已經從上下文加載,那麼就不附加它,否則如果它已經在上下文之外創建,那麼上面的代碼應該工作。 –