可以添加数据但无法删除

时间:2013-06-25 12:24:39

标签: asp.net-mvc entity-framework

我试图以多对一的关系保存和删除对象。

我有以下代码

    [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);
    }

Follow功能有效,但取消关注功能不起作用。

unfollow函数似乎有效,因为它实际上从列表中删除了人,但Update函数不会在数据库中更新它。

我的更新功能是

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

公司类内的关系

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

1 个答案:

答案 0 :(得分:1)

这是否有效

    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是一个挑剔的野兽。