简体   繁体   中英

EF one to many Update

I have some problems update the data with the relationship one to many. Here is My Entity

public class Customer : Entity
{
    public Customer()
    {
        ContactPersons = new List<ContactPerson>();
    }

    /// <summary>
    /// 客户编号
    /// </summary>
    public string Code { get; set; }

    /// <summary>
    /// 客户名称
    /// </summary>
    public string Name { get; set; }


    public ICollection<ContactPerson> ContactPersons { get; set; }
}


/// <summary>
/// 联系人实体
/// </summary>
public class ContactPerson : Entity
{
    /// <summary>
    /// 姓名
    /// </summary>
    public string FullName { get; set; }

    public string Email { get; set; }

    public string QQ { get; set; }

    public virtual Customer Customer { get; set; }
}

In the Configuration class,the code is:

HasMany(f => f.ContactPersons).WithRequired(f => f.Customer).Map(f => f.MapKey("CustomerId")).WillCascadeOnDelete(true);

I think the mapping is right,add or delete works fine,only update throw exceptions.

"Customer_ContactPersons" in AssociationSet is "Deleted". If there are multiple constraints, the corresponding "Customer_ContactPersons_Target" must also is "Deleted".

public void Update(CustomerEditViewModel model)
    {
        var customerDb = _customerRep.GetAll().NotLazy(f => f.ContactPersons).SingleOrDefault(f => f.Id == model.Id);

        //customerDb.ContactPersons.Clear(); can not work either!!

        var count = customerDb.ContactPersons.Count;
        for (var i = 0; i < count; i++)
        {
            customerDb.ContactPersons.Remove(customerDb.ContactPersons.ElementAt(i));
            count--;
        }

        _customerRep.Update(customerDb);
    }

I want to Clear the List of ContactPersons in Customer ,how to...

You are removing the relationship between the Customer and ContactPerson entities without deleting the ContactPerson entity.

Rewrite your method as below to remove the associated ContactPerson entities instead.

public void Update(CustomerEditViewModel model)
{
    var customerDb = _customerRep.GetAll().NotLazy(f => f.ContactPersons).SingleOrDefault(f => f.Id == model.Id);

    foreach(var contactPerson in customerDb.ContactPersons.ToList())
    {
        _customerRep.Delete(contactPerson);
    }

}

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