I struggled with this for a while and cannot find a solution for.
I have an MVC application that uses Entity Framework templates with repositories and work modules. I recently switched from using a network database (Sql Server 2008 R2, where the problem did not seem to exist) to a local database, and started using Entity Framework migrations to work with another developer and did not affect each other by making changes to our models .
My model looks like this:
[Table("Student")]
public class Student
{
[Key]
public int Id { get; set; }
<... other fields ...>
[Required(ErrorMessage = "A student type is required")]
public int StudentTypeId { get; set; }
[Required(ErrorMessage = "A student status is required")]
public int StudentStatusId { get; set; }
[ForeignKey("StudentTypeId")]
public virtual StudentType StudentType { get; set; }
[ForeignKey("StudentStatusId")]
public virtual StudentStatus StudentStatus { get; set; }
}
Every time I try to update the StudentStatus property for Student, I get the following exception:
" , .
ObjectContext . : :
() "StudentStatus.Id" "Student.StudentStatusId" . "
.
student.StudentStatus = null;
student.StudentStatusId = 26;
_studentRepository.Update(student);
_unitOfWork.Commit();
StudentStatus:
var studentStatus = _studentStatusRepository.GetById(26);
student.StudentStatusId = 26;
student.StudentStatus = studentStatus;
_studentRepository.Update(student);
_unitOfWork.Commit();
DataContext.SaveChanges().
StudentType ( ) .
:
public virtual void Update(T entity)
{
try
{
DataContext.Entry(entity).State = EntityState.Modified;
}
catch (Exception exception)
{
throw new EntityException(string.Format("Failed to update entity '{0}'", typeof(T).Name), exception);
}
}
, EF Migrations , ( , , ). , .
, , , , ?
EDIT ( StudentStatus StudentStatusType)
[Table("StudentStatus")]
public class StudentStatus
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Student status name is required")]
[MaxLength(50, ErrorMessage = "Student status name cannot be longer than 50 characters")]
public string Name { get; set; }
public int StudentStatusTypeId { get; set; }
[ForeignKey("StudentStatusTypeId")]
public virtual StudentStatusType StudentStatusType { get; set; }
}
[Table("StudentStatusType")]
public class StudentStatusType
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
2
, , , SQL- Entity Framework:
DataContext.Database.Log = s => Debug.WriteLine(s);
:
UPDATE [dbo].[Student]
SET <... some parameters ...>, [StudentStatusId] = @10, <... some parameters ...>
WHERE ([Id] = @14)
UPDATE [dbo].[Student]
SET <... some parameters ...>, [StudentStatusId] = @10, <... some parameters ...>
WHERE ([Id] = @14)
<... some parameters ...>
<... some parameters ...>
, EF 25, , 26? ? , , ?