Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping association tables in EF 4.1 code first

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 product's specifications?

I currently only have a Product class.

Products Table:
Id
Name
IsActive

ProductSpecification Table:
ProductId
SpecificationId

Specifications Table:
Id
Name
IsActive

ProductSpecifications is an association table. I also have the following defined in my context class:

public DbSet<Product> Products { get; set; }

EDIT

Please see my updated original post. I changed the Id of the Products and Specifications tables.

In my context class I have the following:

public DbSet<Product> Products { get; set; }
public DbSet<Specification> Specifications { get; set; }

In my repository I have the following:

public Product GetById(int id)
{
     return db.Products
          .Include("Specifications")
          .SingleOrDefault(x => x.Id == id);
}

My Product class (partial):

public class Product : IEntity
{
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActive { get; set; }
     public ICollection<Specification> Specifications { get; set; }
}

My Specification class:

public class Specification : IEntity
{
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActive { get; set; }
     public ICollection<Product> Products { get; set; }
}

This was all that I did from Slauma's answer. I did not do the mapping manually as what he said I should, but I first need to understand the following:

Given my classes and tables from above, what exactly does the EF 4.1 naming conventions state on how it handles association tables? The reason why I ask is because I get the following error in my GetById method:

Invalid object name 'dbo.SpecificationProducts'.

EDIT 2

I forgot to mention the following :) A product can have a specification height as value. And for this height I need to specify a value. Like 100 inches. So I modified the ProductSpecifications table to have a value column called SpecificationValue, this column will contain the value 100 inches. How would I modify the code to retrieve this value as well? I need to display it on my view.

like image 337
Brendan Vogt Avatar asked Nov 01 '11 11:11

Brendan Vogt


1 Answers

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.

like image 118
Slauma Avatar answered Oct 06 '22 01:10

Slauma