Entity framework 4 many-to-many insertion?
I'm not very familiar with the many-to-many insertion process using Entity Framework 4, POCO. I have a blog with 3 tables: Post, Comment, and Tag. A Post can have many Tags and a Tag can be in many Posts. Here are the Post and Tag models:
public class Tag
{
public int Id { get; set; }
[Required]
[StringLength(25, ErrorMessage = "Tag name can't exceed 25 characters.")]
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
[Required]
[StringLength(512, ErrorMessage = "Title can't exceed 512 charac开发者_StackOverflow社区ters")]
public string Title { get; set; }
[Required]
[AllowHtml]
public string Content { get; set; }
public string FriendlyUrl { get; set; }
public DateTime PostedDate { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
Now when I'm adding a new post, I'm not sure what would be the right way to do. I'm thinking that I'll have a textbox where I can select multiple tags for that post (this part is already done), in my controller, I will check to see if the tag is already exists or not, if not, then I will insert the new tag. But I'm not even sure based on the models that I've created for EF, will they create a PostsTags table, or they are creating just a Tags and a Posts table and links between the two?
How would I insert the new Post and set the tags to that post? Is it just newPost.Tags = Tags
(where Tags are the one that got selected, do I even need to check to see if they already exists?), and then something like _post.Add(newPost);
?
Thanks.
I think that this is what you want.
var tag = context.Tags.FirstOrDefault(x=>x.Name == name);
if (tag == null)
context.Tags.AddObject(tag = new Tag { Name = name });
if (!post.Tags.Contains(tag))
post.Tags.Add(tag);
Happy New-Year coding))
I would advise against maintaining many-to-many relationships in your database.
You should consider creating a lookup table called something like PostTag
or PostTagLookup
.
This would consist of two columns - PostId
and TagId
.
Entity framework handles lookup tables wonderfully, as mentioned by @Moyo in his answer:
Entity Framework will convert the mapping table into a collection of entities on both sides and the table itself will essentially disappear.
I can't seems to get it working without the Id for the Lookup table, this is what I've done to make it work. Might not be the best and most efficient way but it's working:
public class PostTagLookup
{
public int Id { get; set; }
public int PostId { get; set; }
public int TagId { get; set; }
public virtual Post Post { get; set; }
public virtual Tag Tag { get; set; }
}
精彩评论