Brianvdb
Brianvdb

Reputation: 676

EntityFrameWork ICollection Code First Issue when adding same object

I created a code first database with the following 2 Model classes.

public class Product
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

public class ProductCollection
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }

 }

Now I have the following generic repository (only relevant methods showed)

public class EntityRepository<T> : IRepository<T> where T : class
{
    protected DatabaseContext database;

    public EntityRepository(DatabaseContext database)
    {
        this.database = database;
    }

    public T Add(T t)
    {
        database.Set<T>().Add(t); 
        database.SaveChanges();
        return t;
    }

}

Now when I create a ProductCollection A and add Product B, it gets added like it should. Now when I create a ProductCollection C and add same Product B, it gets added, but gets removed from ProductCollection A.

Code:

ProductCollection productCollection = new ProductCollection()
{
    Name = "Apple Collection",
    Products = new Collection<Product>() {
        productRepository.Get(1)
    },
};

this.productCollectionRepository.Add(productCollection);

Trace.WriteLine(productCollection.Products.Count); // PRINTS 1, LIKE IT SHOULD

ProductCollection productCollection1 = new ProductCollection()
{
    Name = "Apple Collection2",
    Products = new Collection<Product>() {
        productRepository.Get(1)
    },
};

this.productCollectionRepository.Add(productCollection1);

Trace.WriteLine(productCollection.Products.Count); // PRINTS 0, SHOULD PRINT 1, PRODUCT GOT REMOVED
Trace.WriteLine(productCollection1.Products.Count); // PRINTS 1, LIKE IT SHOULD

Any ideas how to solve this?

Upvotes: 0

Views: 525

Answers (1)

Lukas.Navratil
Lukas.Navratil

Reputation: 590

You have to configure the relationship between entities as many-to-many, now Product can be associated with only one ProductCollection.

You can add

public virtual ICollection<ProductCollection> ProductCollections { get; set; }

to your Product class and EF will handle it automatically or you can configure it using FluentApi.

See e.g. http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

Upvotes: 1

Related Questions