Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many-To-Many Relationship in Code-First EF4

How do you represent a many-to-many relationship in the EF4 Code-First CTP3?

For example if I have the following classes:

class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Profile> Profiles { get; set; }
}

class Profile
{
    public int Id { get; set; }
    public string Name { get; set; }
}

In the database there is a UserProfiles table that has the FK for User and FK for Profile. How can I map this?

EDIT: I understand how to to currently map with having a ICollection<User> property on the Profile, but I really don't want to have a an opposite navigation property when it should be "Users have many profiles".

like image 846
TheCloudlessSky Avatar asked Jun 30 '10 11:06

TheCloudlessSky


People also ask

What is many-to-many relationships in code first approach?

A many-to-many relationship occurs when multiple records in one table are associated with multiple records in another table. For example, a many-to-many relationship exists between Book and Category entities.

How do you create a many-to-many relationship in EF core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

How do you create a foreign key relationship in code first approach?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the foreign key table. Thanks for reading this article, hope you enjoyed it.


1 Answers

EDIT: CTP4 was released late yesterday (July 14 2010) and there is now support for this:

modelBuilder.Entity<Post>().HasMany(p => p.Tags).WithMany();


I found out finally that this currently isn't possible. Microsoft is looking to add this feature (only one navigation property).

See this link on the MSDN forums for more information: http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/6920db2b-88c7-4bea-ac89-4809882cff8f

like image 51
TheCloudlessSky Avatar answered Sep 17 '22 15:09

TheCloudlessSky