Cannot insert explicit value for identity column while updating entity

aspnetboilerplate entity-framework entity-framework-6 identity-insert

Question

I am using ASP.NET Boilerplate template.

I want to update Details table, which contains more than one item. If an item exists, it must update, otherwise a new one must be added and all other entries relating to Master primary key in Details table must be deleted. But it is showing an error:

Cannot insert explicit value for identity column in table 'SemesterDetails' when IDENTITY_INSERT is set to OFF

This is the Master table:

public class StudentDegreeCore : Entity<int>
{
    [StringLength(150)]
    [Required(ErrorMessage = "Enter Degree College ")]
    public string DegreeCollege { get; set; }

    [Required()]
    public string CollegeID { get; set; }

    [StringLength(7, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 7)]
    [Required(ErrorMessage = "Enter 10th Pass Year")]
    public string CommencementYear { get; set; }

    public List<StudentSemesterCore> SemesterDetails { get; set; }
}

This is the Details table, represented by the StudentSemesterCore class:

public class StudentSemesterCore
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(150)]
    [Required(ErrorMessage = "Enter Year/Semester")]
    public string YearOrSemester { get; set; }

    [Required()]
    public virtual int StudentDegreeID { get; set; }

    [ForeignKey("StudentDegreeID")]
    public virtual StudentDegreeCore StudentDegreeCore { get; set; }

    [StringLength(4, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
    [Required(ErrorMessage = "Enter Semester Status")]
    public string Status { get; set; }

    [DisplayName("% of Marks")]
    [RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Numbers With Two decimal Place Allowed")]
    public decimal MarkPercentage { get; set; }
}

This is the Update code:

_studentdegreeRepository.Update(st);
CurrentUnitOfWork.SaveChanges();

It shows an error when SaveChanges is called. Actually, I want to update the details if the same value exists, otherwise add new one and all other data relating to the same StudentDegreeID must be removed.

1
0
12/2/2017 9:32:02 AM

Accepted Answer

I tried this

 public override async Task<StudentDegreeDto> Create(StudentDegreeCreateDto input)
            {
                //CheckCreatePermission();
                StudentDegreeCore st = new StudentDegreeCore();
                try
                {

                    StudentDegreeCore core = new StudentDegreeCore()
                    {
                        Id = input.Id,
                        Address1 = input.Address1,
                        Address2 = input.Address2,
                        City = input.City,
                        CollegeID = input.CollegeID,
                        CommencementYear = input.CommencementYear,
                        CompletionYear = input.CompletionYear,
                        CurrentYear = input.CurrentYear,
                        DegreeCollege = input.DegreeCollege,
                        DegreeId = input.DegreeId,
                        OverallPercent = input.OverallPercent,
                        PinCode = input.PinCode,
                        PostBox = input.PostBox,
                        State = input.State,
                        StreamId = input.StreamId,
                        UserId = input.UserId
                    };
                    core.SemesterDetails = new List<StudentSemesterCore>();

                    foreach (var items in input.SemesterDetails)
                    {
                        core.SemesterDetails.Add(new StudentSemesterCore()
                        {
                            GPA = items.GPA,
                            MarkPercentage = items.MarkPercentage,
                            Status = items.Status,
                            UserId = items.UserId ,
                            Id = items.Id,
                            StudentDegreeID = items.StudentDegreeID ,
                            YearOrSemester = items.YearOrSemester,
                            LastModificationTime = DateTime.Now,
                            CreationTime = DateTime.Now
                        });                          
                    }
                    var student = core; //ObjectMapper.Map<StudentDegreeCore>(input);
                    long uid = (AbpSession.UserId == null) ? 0 : Convert.ToInt64(AbpSession.UserId);
                    st = _studentRepository.Get(student.Id);
                    if (st != null && st.Id > 0)
                    {
                        st.DegreeCollege = student.DegreeCollege;
                        st.CollegeID = student.CollegeID;
                        st.CommencementYear = student.CommencementYear;
                        st.CompletionYear = student.CompletionYear;
                        st.LastModificationId = Convert.ToInt32(AbpSession.UserId);
                        st.LastModificationTime = DateTime.Now;
                        st.StreamId = student.StreamId;
                        st.DegreeId = student.DegreeId;
                        st.CurrentYear = student.CurrentYear;
                        st.OverallPercent = student.OverallPercent;
                        st.PinCode = student.PinCode;
                        st.PostBox = student.PostBox;
                        st.State = student.State;
                        st.Address1 = student.Address1;
                        st.Address2 = student.Address2;
                        st.City = student.City;
                        st.SemesterDetails = new List<StudentSemesterCore>();
                        //st.SemesterDetails = student.SemesterDetails;
                        _studentRepository.Update(st);
                        foreach (var items in student.SemesterDetails)
                        {
                            _studentSemesterRepository.InsertOrUpdate(items);
                        }
                        //_studentRepository.Update(st);                   
                        CurrentUnitOfWork.SaveChanges();
                    }
                    else
                    {
                        student.UserId = Convert.ToInt32(AbpSession.UserId);
                        student.CreationId = Convert.ToInt32(AbpSession.UserId);
                        _studentRepository.Insert(student);
                        CurrentUnitOfWork.SaveChanges();
                    }
                }
                catch (Exception ex)
                {

                }
                StudentDegreeDto studentDegreeDto = new StudentDegreeDto()
                {
                    Id = input.Id,
                    Address1 = input.Address1,
                    Address2 = input.Address2,
                    City = input.City,
                    CollegeID = input.CollegeID,
                    CommencementYear = input.CommencementYear,
                    CompletionYear = input.CompletionYear,
                    CurrentYear = input.CurrentYear,
                    DegreeCollege = input.DegreeCollege,
                    DegreeId = input.DegreeId,
                    OverallPercent = input.OverallPercent,
                    PinCode = input.PinCode,
                    PostBox = input.PostBox,
                    State = input.State,
                    StreamId = input.StreamId,
                    UserId = input.UserId
                };
                studentDegreeDto.SemesterDetails = new List<StudentSemesterDto>();
                foreach (var items in input.SemesterDetails)
                {
                    studentDegreeDto.SemesterDetails.Add(new StudentSemesterDto()
                    {
                        GPA = items.GPA,
                        MarkPercentage = items.MarkPercentage,
                        Status = items.Status,
                        YearOrSemester = items.YearOrSemester,
                        LastModificationTime = DateTime.Now,
                        CreationTime = DateTime.Now
                    });
                }
                return studentDegreeDto;
            }
0
12/5/2017 7:47:10 AM

Popular Answer

  1. StudentSemesterCore is not derived from Entity.
  2. You don't need to put Id property in StudentSemesterCore. Remove it.
  3. Add StudentDegreeCoreId to StudentSemesterCore as foreign key reference.


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow