C#实体框架"一个实体对象不能由IEntityChangeTracker&QUOT的多个实例被引用; [英] C# Entity Framework "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

查看:193
本文介绍了C#实体框架"一个实体对象不能由IEntityChangeTracker&QUOT的多个实例被引用;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此错误是抛出了很多,但我不能找到解决方案。我是新来的实体框架和我的第一个方法,我得到这个错误。

This error is thrown a lot, but I can't find the solution. I am new to the Entity Framework and in my first approach I got this error.

这是我有什么。我公司拥有一支一流的和分支类。两个类都有自己的资源库。 。一个公司有一个分支,而一个分支可以有多个公司

This is what I have. I have a company class and a branch class. Both classes have their own repository. A company has one Branch, while one branch can have multiple companies.

在我的GUI我充满了分公司的对象,这是我从我的BranchRepository得到一个组合:

In my GUI I fill a combo with Branch objects, which I get from my BranchRepository:

    public IList<Branch> GetAllBranches()
    {
        var query = _context.Branches;

        IList<Branch> branches = query.ToList();

        return branches;
    }

这是结果是该分支组合框的数据源。

This is result is the datasource of the branch combobox.

当我想挽救公司,我做这样的事情:

When I want to save the company, I do something like this:

company.VisitorAddress = txtVisitAddress.Text;
company.City = txtCity.Text;
company.CompanyName = txtCompany.Text;
company.PhoneNumber = txtPhoneNumber.Text;
company.ZipCode = txtZipcode.Text;
company.Branch = ((Branch)cmbBranches.SelectedItem);
company.Website = txtWebsite.Text;



然后,我打电话给我的公司资料库,以节省我的公司。这里是保存方法如下:

Then, I call my company repository to save my company. Here is what the save method looks like:

public bool Save(Company company)
{
    _context.AddToCompanies(company);   // <-- This is where the error is thrown.
    _context.SaveChanges();

    return true;
}

当调用保存的方法,我得到错误的实体对象不能通过IEntityChangeTracker的多个实例引用。

When the save method is invoked, I get the error 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker'.

显然,我做错了什么,但什么?

Clearly I'm doing something wrong, but what?

推荐答案

你为每个存储库中创建新的的ObjectContext 实例?这可能是问题的根源,因为当你添加领域为公司尝试将其添加到的ObjectContext 实例,不能做,因为它仍然关系到 ObjectContext的实例用来填充组合框。要走的路是分享您的资料库中的ObjectContext 实例。另一种可能性是,以分离从第一库科,但它可以有其他consequencies。

Do you create new ObjectContext instance for each your repository? That could be source of problem because when you add Branche to Company it tries to add it to ObjectContext instance which cannot be done because it is still related to ObjectContext instance used to fill combobox. The way to go is to share ObjectContext instance among your repositories. Other possibility is to Detach Branch from first repository but it can have other consequencies.

这篇关于C#实体框架&QUOT;一个实体对象不能由IEntityChangeTracker&QUOT的多个实例被引用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆