0

Here is my Entity-Model

[Table("WP_Schraenke")]
public class Cabinet {
    [Column("Id")]
    public int Id { get; set; }

    [Column("Standort")]
    public string Location { get; set; }

    [Column("Nummer")]
    public int Number { get; set; }

    [Column("MonteurNr")]
    public string PersonelNumber { get; set; }

    public Employee Employee { get; set; }

    [Column("Status")]
    public CabinetState State { get; set; }
}

PersonelNumber is a foreignkey defined like

modelBuilder.Entity<Cabinet>()
    .HasOne(e => e.Employee)
    .WithMany()
    .HasPrincipalKey(e => e.PersonelNumber)
    .HasForeignKey(e => e.PersonelNumber);

I attach and save a entity on this way:

public int Save(CabinetDto cabinet) {
    var ctx = this.ContextProviderService.GetE3kContext();
    var entity = new Cabinet {Id = cabinet.Id};
    ctx.Cabinets.Attach(entity);

    entity.Location = cabinet.Location;
    entity.Number = cabinet.Number;
    entity.PersonelNumber = cabinet.Employee?.PersonelNumber;

    ctx.SaveChanges();
    return entity.Id;
}

This is working, but when I set entity.PersonelNumber to null (all other values are unchanged), SaveChanges() isn't saving this to the database.

BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • What happens if you set employee and personelnumber to null? – niQu Dec 07 '21 at 08:05
  • What is your C# version? With C# 8 and .NET6, now it is possible to create string nullable. That may be the issue. Can your try to change public string PersonelNumber { get; set; } to public string? PersonelNumber { get; set; } Documentation here: https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references Similar problem here: https://stackoverflow.com/questions/67693610/ef-core-fail-to-load-entity-with-nullable-string-value – Emre Utku Solak Dec 07 '21 at 08:18
  • Does this answer your question? [How to update only one field using Entity Framework?](https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework) – Svyatoslav Danyliv Dec 07 '21 at 10:46
  • Have you tried configuring `PersonelNumber` as not required explicitly? Also, You could try to mark it's state manually as `Modified` - I am not sure, but it could be helpful when dealing with nullable fk,. – quain Dec 07 '21 at 14:36

0 Answers0