0

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

我有以下代码

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

关注功能有效,但取消关注功能无效。

取消关注功能似乎有效,因为它实际上从列表中删除了此人,但更新功能不会在数据库中更新它。

我的更新功能是

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; }
    }
4

1 回答 1

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

于 2013-06-25T12:46:18.087 回答