this is my entity:
public partial class Student
{
public string Code { get; set; }
public int Year { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
Config:
HasKey(e => new { e.Code, e.Year});
Property(b => b.Code).HasColumnName("CODE").IsUnicode(false).HasMaxLength(20).IsRequired();
Property(b => b.Year).HasColumnName("YEAR").IsRequired();
Property(b => b.Name).HasColumnName("NAME").IsUnicode(false).HasMaxLength(50);
Property(b => b.Gender).HasColumnName("GENDER").IsUnicode(false).HasMaxLength(2).IsRequired();
The gender field also has the required option. In my update I only want to update the name field:
var student = new Student
{
Code = "WRK",
Year = 2018,
Name = "Test Name"
};
_context.Student.Attach(student);
_context.Entry(student).Property(x => x.Name).IsModified = true;
_context.SaveChanges();
On SaveChanges it gives a DbEntityValidationException, saying the gender field is required. Although I don't want to update it, but keep the existing value from the database.
Is there a proper solution without first querying the database to get the existing value for that gender field?
Thanks.
I use solution like this:
Public Overrides Function SaveChanges() As Integer
For Each changedEntity In Me.ChangeTracker.Entries
Select Case changedEntity.State
Case EntityState.Modified
Select Case If(changedEntity.Entity.GetType.Namespace = "System.Data.Entity.DynamicProxies", changedEntity.Entity.GetType.BaseType, changedEntity.Entity.GetType)
Case GetType(Student)
changedEntity.Property("Gender").IsModified = False
End Select
Next
Return MyBase.SaveChanges()
End Function