Wesley Skeen
Wesley Skeen

Reputation: 8285

Can add data but cannot delete

I am trying to save and delete objects in a many to one relationship.

I have the following code

    [System.Web.Http.HttpPost]
    public void FollowPerson(int personId, int companyId)
    {
        var uow = new Uow();
        var person = uow.People.GetById(personId);
        var company = uow.Companies.GetById(companyId);

        company.People.Add(person);
        uow.Companies.Update(company);
    }

    [System.Web.Http.HttpDelete]
    public void UnFollowPerson(int personId, int companyId)
    {
        var uow = new Uow();
        var person = uow.People.GetById(personId);
        var company = uow.Companies.GetById(companyId);

        company.People.Remove(person);
        uow.Companies.Update(company);
    }

The Follow function works but the unfollow function does not.

The unfollow function seems to work, as it actually removes the person from the list but the Update function does not update it in the database.

My update function is

public void Update(Company company)
    {           
        var compToUpate = DbSet.FirstOrDefault(c => c.Id == company.Id);
        DbContext.Entry(compToUpate).CurrentValues.SetValues(company);
        DbContext.SaveChanges();
    } 

Relationship within Company class

private ICollection<Person> _people;
public virtual ICollection<Person> People
    {
        get { return _people; }
        set { _people = value; }
    }

Upvotes: 0

Views: 71

Answers (1)

CodeMonkeyForHire
CodeMonkeyForHire

Reputation: 362

Does this work

    var company = uow.Companies.GetById(companyId);
      ...depending on if you have lazy loading, might need to do a load on People
   var person = company.People.where(p=> p.id==personId).first();
   company.People.Remove(person);

EF is a finicky beast.

Upvotes: 1

Related Questions