Code First update fields without required field

ef-code-first entity-framework-6


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; }


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.Entry(student).Property(x => x.Name).IsModified = true;


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?


9/12/2018 8:06:25 AM

Popular Answer

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
    Return MyBase.SaveChanges()
End Function
9/25/2018 11:30:58 AM

Related Questions


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