简体   繁体   中英

Replacing detached child collection EF Core

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.

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM