I have 2 entity classes, first class:

public class Vnz { [Key] public int Id_Vnz { get; set; } [Required, MaxLength(50)] public string NameVnz { get; set; } [Required, MaxLength(20)] public string Type { get; set; } [MaxLength(100)] public string Address { get; set; } public string Deckrib { get; set; } public string History { get; set; } public List<Vidilena> vidilenas { get; set; } } 

and second class:

 public class Vidilena { [Key] public int Id_Vid { get; set; } [Required, MaxLength(50)] public string NameVid { get; set; } [MaxLength(20)] public string Shifr { get; set; } [Required, MaxLength(50)] public string Zaviduvach { get; set; } [Required, MaxLength(20)] public string Telephone { get; set; } public string Decrib { get; set; } [Required] public Vnz Vnz { get; set; } } 

context is as follows:

 class StudentContext : DbContext { public DbSet<Vnz> Vnzs { get; set; } public DbSet<Vidilena> Vidilenas { get; set; } } 

When adding Vnz data to the table, everything works fine, but when I add data to Vidilena, Vnz data is duplicated (a copy is created):

 readonly StudentContext db = new StudentContext(); Vidilena vid = new Vidilena() { Decrib = tbDescrib.Text, NameVid = tbName.Text, Shifr = tbShifr.Text, Zaviduvach = tbZaviduvach.Text, Telephone = tbTelephone.Text, Vnz = db.Vnzs.Where(d=>d.Id_Vnz.Equals(VnzId)).FirstOrDefault() }; await comand.VidilAddAsync(vid); 

here is the method code:

 public async Task VidilAddAsync(Vidilena vidilena) { using (StudentContext db = new StudentContext()) { try { db.Vidilenas.Add(vidilena); await db.SaveChangesAsync(); Boxes.Information("Успішно додано!"); } catch (Exception ex) { Boxes.Error(ex.Message); } } } 

how to remove duplicates?

  • Do you fill in the Vnz field in the Vidilena table? Maybe duplicates are taken from it? - Vitaliy Shebanits
  • Comment out the line Vnz = db.Vnzs.Where(d=>d.Id_Vnz.Equals(VnzId)).FirstOrDefault() - AK
  • and then how will the link navigation properties go? I tie one to many with this line (the same link to another table) - Yarik08
  • You need to create a field VnzId - which for some reason you have not created before. You also need an empty Vnz constructor that fills in vidilenas = new List<Vdilena>(); . - AK
  • Vnzid need to create vidilena class? - Yarik08 pm

0