实体框架4多到许多插入? [英] Entity framework 4 many-to-many insertion?

查看:183
本文介绍了实体框架4多到许多插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是很熟悉使用实体框架4,POCO许多一对多插入过程。我有3个表一个博客:帖子,评论和标签。 A 发表可以有很多的代码代码可以在许多文章。以下是在发布代码模型:

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 characters")]
    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; }
}

现在,当我加入一个新的岗位,我不知道什么是应该做的方式。我在想,我将有一个文本框,在那里我可以为后选择多个标签(这部分已经完成),在我的控制器,我会检查,看看是否标记已经存在与否,如果没有,那么我将插入新的标签。但是,我甚至不知道基于我为EF创建的模型,他们将创建一个PostsTags表,或者他们正在创建只是两者之间的标签和帖子表和链接?

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?

我将如何插入新的发布并设置标签,该职位?难道仅仅是 newPost.Tags =标签(其中标签是选定了这一个,我什至需要检查,看看他们是否已经存在?),然后像 _post.Add(newPost);

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);?

感谢。

推荐答案

我不能似乎得到它没有标识工作的查找表,这是我做了什么,使其工作。也许不是最好的,最有效的方式,但它的工作:

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; }
}

这篇关于实体框架4多到许多插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆