Refresh EF 6 DBContext

c# entity-framework entity-framework-6

Question

I am working with Entity Framework 6 and I have an product object that has a list of variants like so:

public class Product
{
    public int ProductId { get; set;}

    public virtual ICollection<Variant> Variants { get; set;}

    ... other properties
}

public class Variant
{
    public int VariantId { get; set;}

    public int ProductId { get; set;}

    public virtual Product Product { get; set;}

    public int StoreId { get; set;}

    ... other properties
}

And I use this to get the products from the context:

public static GetProducts()
{
    using (MyDBContext context = new MyDBContext())
    {
        return context.Products.Include(p => p.Variants);
    }
}

Now this all works fine and when I get the Product it comes back with the variants. However, this morning I foolishly used the Product from the context instead of a DTO and filtered the variants based on a StoreId and now whenever I get a Product, it only returns the variants for that store (even though I never committed any changes).

I have checked the db and all the variants are still there so how do I reset my context so that I get all variants again.

I have tried the following:

  • resetting iis
  • cleaning and rebuilding the solution
  • changing the object to return an extra property
  • reloading the product using:

    foreach (Product product in context.Products)
    {
        context.Entry(product).Reload();
    }
    

But nothing seems to work, is there anything else I need to do to reset the context?

1
0
4/23/2015 2:59:45 PM

Accepted Answer

As it turns out it was a config error with the variant entity rather than the filtered context. I was only using the VariantID as the Key but as there were multiple variants with the same id, it was overriding the following variants with the same values as the first one with that id when it was mapping the objects back after the query (making it look as if there was only the store I had filtered).

I fixed this by making the key unique to the store and the variant id:

HasKey(v => new {v.VariantId, c.StoreId});
0
4/24/2015 2:10:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow