There is a post that says how to do this but it does not explain how to work with it.
We have a class "Persoon" (dutch) in English 'Person' and we want to add a friend (vriend in Dutch) with an ICollection who's also a 'Person'
We have the following code in our domain class Persoon:
public virtual ICollection<Persoon> Vrienden { get; set; }
this is because one person can have many friends (vrienden in Dutch)
For implementing our Icollection and creating our friendship table we have used the following code:
modelBuilder.Entity<Persoon>()
.HasMany(m => m.Vrienden)
.WithMany()
.Map(w => w.ToTable("Vriendschap")
.MapLeftKey("PersoonID")
.MapRightKey("VriendID"));
Now is the question, we have created the friendship table but how can we now add Person's to the friendship table with PersoonID (personID) & vriendID (friendID). I know that you can use 'vrienden.Add(entity)' but I don't know how to use ith within a new controller like friendshipcontroller is this not necessary ?
How do we have to implement this in our controllers and views ? so that we can add, edit, delete en see a list from the collection ?
Thanks in advance!!
You can apply CRUD operations using code like the example you gave in your question:
person.Vrienden.Add(friend);
person.Vrienden;
person.Vrienden.Remove(friend);
otherPerson.Vrienden.Add(friend);
person.Vrienden.Remove(friend);
However, since you want to be able to query for all friendships, perhaps what you're wanting is to materialise the Friendship
concept in your domain model:
public class Friendship
{
public Persoon FriendA { get; set; }
public Persoon FriendB { get; set; }
}
Adjust Persoon
and its mapping so that Vrienden
is an ICollection<Friendship>
. Then adjust your mapping to be one-to-many (one person has many friendships).
Now you can query for all friendships and apply CRUD operations to Friendship
s directly. Note that you'll need to be careful to prevent duplicate friendships since you could have two friendships between the same pair of friends but with reversed order.