maztt
maztt

Reputation: 12294

entity framework many to many inserts code first

this is my model

    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) Is this the right many to many configuration in EF 4.1 without mentioning the modelbinder for many to many.

2) if i have completed the many to many configuration using dataannotation why the data is not inserting in 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) I do have to define modelbinder to have many to many inserts or delete or update?

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

Upvotes: 0

Views: 1661

Answers (1)

robrich
robrich

Reputation: 13205

Change your models to this:

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

and then save like so:

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 will create the intermediate table in the db and populate it nicely automatically.

Upvotes: 2

Related Questions