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

Smithy
  • 2,170
  • 6
  • 29
  • 61

1 Answers1

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; }
Community
  • 1
  • 1
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • You're right, it worked. I also added public ICollection Products { get; set; } to my Category model to create the correct table and relationships. p.s. thanks for the lazy loading tip too :) – Smithy Mar 08 '13 at 09:22
  • actually, in my View Models (these are my DTOs) should i continue to use Icollection stick with Ienumerable or doesn't it matter? – Smithy Mar 08 '13 at 09:23
  • 1
    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. – Davin Tryon Mar 08 '13 at 09:27