Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1 Code First - Define many-to-many using data annotations only

Is it possible to define a many-to-many relationship in Entity Framework 4.1 (Code First approach) using Data Annotations only, without model builder?

For example, something like:

Product = { Id, Name, ... }
Category = { Id, Name, ... }
ProductCategory = { ProductId, CategoryId }

You get the picture.

I don't want to have an intermediate entity ProductCategory in the context with two many-to-ones since I don't have any additional data, just the two FKs. Also, I should be able to define table name for the intermediate table for use with an existing database.

like image 461
Boris B. Avatar asked Jun 07 '11 22:06

Boris B.


People also ask

How do I map a one to many relationship in Entity Framework?

“HasMany” and “WithMany” method is used to define one-to-many or many-to-many relation in entity framework. We can configure one-to-many relationships between People and PeopleAddress using Fluent API by the following code in the model class: protected override void OnModelCreating(DbModelBuildermodelBuilder) {

Which data annotations attribute can be used to define a primary key property?

You can use the key annotation to specify which property is to be used as the EntityKey. If you are using code first's database generation feature, the Blog table will have a primary key column named PrimaryTrackingKey, which is also defined as Identity by default.


1 Answers

It is possible to define many-to-many with default conventions or with data annotations but it is not possible to change mapping to junction table (table's name and columns) without model builder. Simple many-to-many:

public class Product
{
    public int Id { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

For using annotations you can use:

public class Product
{
    [Key]
    public int Id { get; set; }
    [InverseProperty("Products")]
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key] 
    public int Id { get; set; }
    [InverseProperty("Categories")]
    public virtual ICollection<Product> Products { get; set; }
}

If you need to control mapping of junction table to existing database you need modelBuilder. Data annotations are not as powerful as fluent API.

like image 51
Ladislav Mrnka Avatar answered Sep 22 '22 05:09

Ladislav Mrnka