I need to map a many-to-many relationship using Entity Framework Code First. Its a standard socialnetworking FriendRequests mapping. A User Object has a Collection of FriendRequests of type List<User>. In the database I’m using a join table for the relationship as follows:
CREATE TABLE dbo.FriendRequests(
UserId INT NOT NULL FOREIGN KEY REFERENCES dbo.Users(id),
FriendId INT NOT NULL FOREIGN KEY REFERENCES dbo.Users(id),
RequestDate SMALLDATETIME NOT NULL DEFAULT GETUTCDATE())
GO
ALTER TABLE dbo.FriendRequests ADD PRIMARY KEY (UserId,FriendId)
GO
How do I map the user object in Entity Framework Code First to enable a Collection via a join table?
You can try it this way:
Mapping with Fluent API:
Because of the
RequestDateproperty in the link table you cannot map this as a many-to-many relationship. Instead you need two one-to-many relationships as shown above.Possibly you need to disable cascading delete, I am not sure. You can do this by appending
.WillCascadeOnDelete(false)at the end of the two one-to-many mappings.Edit
To your comment: If you remove the
RequestDatecolumn you can create your model with a many-to-many relationship. You don’t need theFriendRequestentity in this case:Mapping with Fluent API: