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 relatio开发者_开发百科nship 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?)
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.
Hopefully someone with more expertise in EF will be able to help you, but if it were me in this situation, I would model the M-M relationship myself (so, modelling the linking table). This way, you can have
myPost.PostTags.Add(new PostTagLink(){
TagID = 1
});
But then you now have to deal with the extra link table object. On the flipside, if you were going to add more properties to the relationship you'd have to do this anyway.
If there is a better way to work around this, I'd like to know too.
Why are you saying it is inefficient. If you declaring it as Virtual it will not loaded until you access it when you have enabled lazy loading. Let say if you have list of Id values. Then when you want to load all the list you need to call getById
for all the values. That is very inefficient than using the lazy loading.
精彩评论