实体框架首先是多对多插入代码

时间:2012-05-04 06:30:22

标签: asp.net-mvc entity-framework entity-framework-4.1

这是我的模特

    public class Post 
    {
    public long PostID { get; set; }  

    [Required]
    [MaxLength(255)]
    public string Title { get; set; }     
    }    

    public class Tag
    {     
    public long TagID { get; set; }
    [Required]
    [Display(Name = "Tag Name")]
    [MaxLength(30)]
    public string TagName { get; set; } 
    public bool IsActive { get; set; }
    }

   public class TagPost
   {    
    public long TagPostID { get; set; }     
    public long PostID { get; set; }      
    public long TagID { get; set; }

    [ForeignKey("PostID")]
    public virtual Post Posts { get; set; }
    [ForeignKey("TagID")]
    public virtual Tag Tags { get; set; }
    }

1)这是EF 4.1中正确的多对多配置,而不提及多对多的模型绑定器。

2)如果我使用dataannotation完成了多对多的配置,为什么数据没有插入tagpost。

  public void InsertPostQuestion(Post post,List<string> tags)
  {

        context.Posts.Add(post);
        foreach (string tag in tags)
        {
            Tag tagr = new Tag();
            tagr.TagName = tag;
            tagr.IsActive = true;
            context.Tags.Add(tagr);

        }           
        context.SaveChanges(); 

    }

3)我必须定义modelbinder以进行多对多插入或删除或更新?

 modelBuilder.Entity<Post>().
        HasMany(c => c.Tags).
        WithMany(p => p.Posts).
        Map(
        m =>
        {
            m.MapLeftKey("PostID");
            m.MapRightKey("TagID");
            m.ToTable("TagPost");
        });

1 个答案:

答案 0 :(得分:2)

将模型更改为:

public class Post 
{
public long PostID { get; set; }  

[Required]
[MaxLength(255)]
public string Title { get; set; }  

public bool IsActive { get; set; }

public virtual List<Tag> Tags { get; set; }
}

public class Tag
{     
public long TagID { get; set; }
[Required]
[Display(Name = "Tag Name")]
[MaxLength(30)]
public string TagName { get; set; } 
public bool IsActive { get; set; }

public virtual List<Post> Posts { get; set; }
}

然后像这样保存:

public void InsertPostQuestion(Post post,List<string> tags)
{
    context.Posts.Add(post);
    foreach (string tag in tags)
    {
        // TODO: If tag has a unique index on TagName, see if it exists first
        Tag tagr = new Tag();
        tagr.TagName = tag;
        tagr.IsActive = true;
        context.Tags.Add(tagr);
        post.Tags.Add(tagr);
    }           
    context.SaveChanges(); 
}

EF将在数据库中创建中间表并自动填充它。