1

I've set up Entity Framework Code First with the Generic Repository Pattern.

Here are my models:

public interface IEntity {
    int Key { get; set; }
}

public class Product : IEntity {
    public int Key {
        get {
            return ID;
        }
        set {
            ID = value;
        }
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public IEnumerable<Category> Category { get; set; }

}

public class Category : IEntity {
    public int Key {
        get {
            return ID;
        }
        set {
            ID = value;
        }
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public int ParentID { get; set; }

}

Here is my context that hooks into my generic repo:

public class EntitiesContext : DbContext, IDbContext {

    public DbSet<Product> Products { get; set; }
    public new IDbSet<T> Set<T>() where T : class {
        return base.Set<T>();
    }
}

As you can see Product has a IEnumerable of Category. If I were to create a database to match this is would be like so:

Product - ID - Name - etc.

Category - ID - Name - etc.

ProductCategories - ProductID - CategoryID

How come when my database is created that there is no joining table?

enter image description here

1 Answer 1

1

I'm pretty sure it is because you are defining the collection as an IEnumerable<T>. I think that Entity Framework needs at least an ICollection<T> to make the relationship. This SO post covers most of it.

So, change this:

public IEnumerable<Category> Category { get; set; }

To this:

public ICollection<Category> Category { get; set; }

Further, if you want to lazy load the collection, then also make it virtual:

public virtual ICollection<Category> Category { get; set; }
Sign up to request clarification or add additional context in comments.

3 Comments

You're right, it worked. I also added public ICollection<Product> Products { get; set; } to my Category model to create the correct table and relationships. p.s. thanks for the lazy loading tip too :)
actually, in my View Models (these are my DTOs) should i continue to use Icollection stick with Ienumerable or doesn't it matter?
I would suggest to use the 'lightest' object possible. You should be able to set an IEnumerable from an ICollection since ICollection inherits from IEnumerable. So, the choice is up to you. ICollection is more efficient if you are indexing into the collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.