Code First update fields without required field

ef-code-first entity-framework-6


This is me, the thing.

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 mandatory choice is also included in the gender field. I simply want to change the name field in my update.

var student = new Student
   Code = "WRK",
   Year = 2018,
   Name = "Test Name"


_context.Entry(student).Property(x => x.Name).IsModified = true;


The gender field is necessary, and a DbEntityValidationException is issued when changes are saved. I want to maintain the current value from the database rather than updating it.

Is there a suitable alternative that doesn't need first requesting the value for that gender column from the database?


9/12/2018 8:06:25 AM

Popular Answer

I use a remedy 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