I\'m not sure how to map the following tables below in EF 4.1 code first
and what objects I need representing the tables. How would I retrieve a list of the pr
In a many-to-many relationship you only define classes for the entities you want to associate but not an entity for the association table. This table is "hidden" in your model and managed by Entity Framework automatically. So you can define these classes:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public ICollection<Specification> Specifications { get; set; }
}
public class Specification
{
public int SpecificationId { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
This is usually enough to define a many-to-many relationship. EF would create a join table from this mapping. If you already have such a table in the database and its naming doesn't follow exactly the naming conventions of Entity Framework you can define the mapping manually in Fluent API:
modelBuilder.Entity<Product>()
.HasMany(p => p.Specifications)
.WithMany(s => s.Products)
.Map(c =>
{
c.MapLeftKey("ProductId");
c.MapRightKey("SpecificationId");
c.ToTable("ProductSpecification");
});
Edit
You can then load the specifications of a product by using Include
for example:
var productWithSpecifications = context.Products
.Include(p => p.Specifications)
.SingleOrDefault(p => p.ProductId == givenProductId);
This would load the product together with the specifications. If you only want the specifications for a given product id you can use the following:
var specificationsOfProduct = context.Products
.Where(p => p.ProductId == givenProductId)
.Select(p => p.Specifications)
.SingleOrDefault();
...which returns a collection of specifications.
Edit 2
The naming conventions of EF Code-First will assume a name of the join table built as combination of the two related class names and then pluralize it. So, without the explicite mapping to your table name ProductSpecification
EF would assume ProductSpecifications
(Plural) and build queries with that name as table name. Because this table doesn't exist in the database you get the exception "Invalid object name 'dbo.SpecificationProducts'." when you run a query. So, you must either rename the table in the database or use the mapping code above.
Edit 3
I would strongly recommend to use the explicite mapping in any case because the join table name EF assumes depends on the order of the DbSets in your context. By changing the order of those sets the join table could be SpecificationProducts
. Without the explicite mapping to a fixed table name a (usually unimportant) swapping of the sets in the context could break your working application.