Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First: Adding to Many to Many relationship by ID

I have a Many-To-Many relationship defined like this:

public class Post {    //NOT SHOWN: Other properties    public virtual ICollection<Tag> Tags { get; set; } } 

All the examples I see would add to the many-to-many relationship like this:

//Get the tag with ID of 1 var tag = context.Tags.Find(1); // associate tag with ID of 1 with myPost myPost.Tags.Add(tag); 

But this seems tedious/inefficient if I just know the id of the tag(s) I would like to associate with my post.

Ideally, I would just like to expose a List<int> TagIds on my Post entity and be able to add Tags by adding the Tag Ids to the list, but I've been unable to determine if this is possible using EF Code First.

Bottom line: What's the best way to add items to a many to many relationship given I just have the ids of the entities I want to relate. (e.g. if I have a list of Tag IDs, what's the best way to relate those Tags to a Post?)

like image 576
Kevin Krueger Avatar asked Sep 19 '11 23:09

Kevin Krueger


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) {

How do I code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…


1 Answers

Use code like this:

// Existing post without loading it from the database var myPost = new Post() { Id = ... }; context.Posts.Attach(post);  // For each id of existing tag  foreach (int tagId in someExistingTagIds) {     var tag = new Tag() { Id = tagId };     context.Tags.Attach(tag);      // Make a new relation     post.Tags.Add(tag); }  context.SaveChanges(); 

This will allow you to create a M-N relation over existing entities without loading anything from the database. You just need to know Ids of existing entities.

like image 109
Ladislav Mrnka Avatar answered Sep 23 '22 06:09

Ladislav Mrnka