niico
niico

Reputation: 12789

ASP.NET MVC 4, EF5, Store additional data in many to many junction table

I have a Code First MVC 4 Web app - there's a many to many relationship between Places:

public virtual int PlaceID { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<User> Followers { get; set; }

and Users:

public virtual int UserID { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Place> Places { get; set; }

Users can 'follow' many places, places can have many followers.

I would like to store additional information about the relationship - say a rating. So a user could have a rating for each place they follow, of between 1-10, say.

How can I achieve that - including CRUD operations (Code First, Entity Framework 5).

Thanks.

Upvotes: 2

Views: 512

Answers (2)

Amin Saqi
Amin Saqi

Reputation: 18977

You must create a junction table and add extra info to it.

Till now, there is no way to create a CRUD master-detail controller with related views.

You should follow the answer I provided to this question of yours...

Upvotes: 0

Michael Gattuso
Michael Gattuso

Reputation: 13210

You will need to replace the many-to-many with two one-to-many relationships to an intermediate class that has the rating property which could be defined as below (you may need to add navigation attributes):

Create an intermediate class

public class UserPlaceRelationship {
  public virtual int PlaceID { get; set; }
  public virtual int UserID { get; set; }
  public virtual Place Place { get; set; }
  public virtual User User { get; set; }
  public virtual int Rating { get; set; }
}

Update your places class:

public virtual int PlaceID { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<UserPlaceReationship> UserRelationships { get; set; }

and your users class:

public virtual int UserID { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<UserPlaceReationship> PlaceRelationships { get; set; }

Querying will be a little trickier as you will have to now navigate through the intermediate class.

Upvotes: 1

Related Questions