简体   繁体   中英

Cannot save many-to-many Entity Framework

I have a simple many-to-many relational database with these entities:

public class Product
{
    public Product()
    {
        this.Category = new HashSet<Category>();
    }

    // just other fields...
    public virtual ICollection<Category> Category { get; set; }
}

public class Category
{
    public Category()
    {
        this.Product = new HashSet<Product>();
    }

    // other fields
    public virtual ICollection<Product> Product { get; set; }
}

I'm trying to save a product, but it throws an exception:

System.InvalidOperationException: 'The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.'

My code:

public void SaveProduct(Product product, IEnumerable<Category> categories)
{
    if (product.ProductID == null)
    {
        product.ProductID = RandomKeyGeneration();
        context.Products.Add(product);
        context.Products.Attach(product);

        foreach (var cat in categories)
            product.Category.Add(cat);
    }

    context.SaveChanges();
}

I googled and tried to solve this issue, but it still didn't work.

An entity object category was referenced by multiple instances of my context class. The problem was in controller, where I used two repositories: one for Products, another - Category. And in the both classes I declare instance of context. Because of this, there were declared two instances of context and was thrown an exception.

It's my fault and inattentiveness. Question closed.

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