Replacing detached child collection EF Core

asp.net-core-webapi c# entity-framework-core

Question

public class PhoneNumber {
  public string Number {get; set;}
  public string Type {get; set;}
}

public class Customer {
   public ICollection<PhoneNumber> phones {get; set;}
}

I am posting(putting) a Customer object to my webapi. Whatever phone numbers are included in the posted object are the only phone numbers I want saved in the database. If there were previously numbers in the db for that customer, I want them deleted.

_context.Update(model);

I have tried the above method but it will only add or edit existing phone numbers. Numbers that exist in the db but not the posted object are not deleted.

1
0
6/6/2019 6:01:29 PM

Popular Answer

You can try to modify your entities to define composite key for PhoneNumber which would consist of PhoneNumber's Id and foreign key to Customer :

public class Customer
{
    [Key]
    public int CustomerId { get; set; }
    public ICollection<PhoneNumber> phones { get; set; }
}

public class PhoneNumber
{
    [Key, ForeignKey("Customer"), Column(Order = 1)]
    public int CustomerId { get; set; }

    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PhoneNumberId { get; set; }
    public string Number { get; set; }
    public string Type { get; set; }

    public Customer customer { get; set; }
}

To configure composite key , use Fluent API configuration in DbConext's overriden method OnModelCreating :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

    modelBuilder.Entity<PhoneNumber>()
        .HasKey(c => new { c.CustomerId, c.PhoneNumberId });
}

The update your database : Add-migration , Update-Database .

Then after get entities in your api , you can update the Customer and child collections like :

Customer cs = new Customer();
cs.CustomerId = 1;
cs.name = "gg";
cs.phones = new List<PhoneNumber>();

cs.phones.Add(new PhoneNumber() { CustomerId = 1, Number = "12", Type = "gg" });

cs.phones.Add(new PhoneNumber() { CustomerId = 1, Number = "44", Type = "TT" });

var customer = db.customers.Include("phones").Single(o => o.CustomerId == cs.CustomerId);
customer.phones = cs.phones;

db.SaveChanges(); 
0
6/7/2019 4:18:26 AM


Related Questions





Related

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