0

这是我的模型

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

1 回答 1

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 将在数据库中创建中间表并自动很好地填充它。

于 2012-05-04T06:37:33.693 回答