How to insert data in many to many relationship

user1740381

I am using code first database model in my project. I am stuck in a many to many relationship insert issue. Here is my database schema:

public class Question
{
  public int Id { get; set; }
  .....
  .......

  [CustomRequiredValidation]
  Public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
  public int Id { get; set; }
  public string Name { get; set; }
  public DateTime CreateDate { get; set; }
  public DateTime LastEditDate { get; set; }
  .....
  .......


  Public virtual ICollection<Question> Questions { get; set; }
}

Now in form post i am sending Question object containing Tags. But tag object contains only name and id of the already saved tags. Now can anyone please tell me how i can insert my Question object in the database so that Many to Many relational table between Question and Tag will also get entry ??

Edit :

I am adding the validation attribute on the navigation collection property (Tags in Question entity). Is this correct place to validate tags for Question ??

Wouter de Kort

What you can do is attach your Tag objects to your context before saving changes. You do this by using context.Tags.Attach(tag). That way, Entity Framework knows that your entity already exists and won't try to insert a duplicate.

Here is a console application that demonstrates this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

class Program
{
    static void Main(string[] args)
    {
        using (MyContext ctx = new MyContext())
        {
            ctx.Database.Delete();

            Question q1 = new Question
            {
                Title = "Title1",
                Tags = new List<Tag> 
                    { 
                        new Tag {Name = "Tag1", CreateDate = DateTime.UtcNow, LastEditDate = DateTime.UtcNow },
                        new Tag {Name = "Tag2", CreateDate = DateTime.UtcNow, LastEditDate = DateTime.UtcNow }, 
                        new Tag {Name = "Tag3", CreateDate = DateTime.UtcNow, LastEditDate = DateTime.UtcNow }, 
                    }
            };

            ctx.Questions.Add(q1);
            ctx.SaveChanges();
        }

        Question q2 = new Question
            {
                Title = "Title1",
                Tags = new List<Tag> 
                    { 
                        new Tag {Id = 1, Name = "Tag1"},
                    }
            };

        using (MyContext ctx = new MyContext())
        {
            foreach (Tag t in q2.Tags)
            {
                DbEntityEntry<Tag> entry = ctx.Entry(t);
                if (entry.State == System.Data.EntityState.Detached)
                {
                    ctx.Tags.Attach(t);
                }
            }

            ctx.Questions.Add(q2);
            ctx.SaveChanges();
        }
    }
}

public class Question
{
    public int Id { get; set; }

    public string Title { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime LastEditDate { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Tag> Tags { get; set; }
    public DbSet<Question> Questions { get; set; }
}

After running this console application you will see that a new link between your second question and the first tag is inserted into the QuestionsTag table.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to insert and fetch to-many relationship entities in core data

From Dev

Doctrine + Zend Framework 2: Insert array of data in a many to many relationship

From Dev

coreData insert to to many relationship

From Dev

coreData insert to to many relationship

From Dev

How to Insert, Update, Delete in a one to many relationship?

From Dev

MySQL - How to insert into table that has many-to-many relationship

From Dev

How to insert into associative table in many to many relationship by Hibernate?

From Dev

how to flatten many to many relationship

From Dev

how to query a many to many relationship?

From Dev

How to save many to many relationship?

From Dev

how to flatten many to many relationship

From Dev

Bulk Insert Many-to-Many Relationship

From Dev

INSERT/DELETE examples in a many-to-many relationship

From Dev

PostgreSQL insert array many-to-many relationship

From Dev

How to retrieve data from many to many relationship in Django

From Dev

How to query a pivot table data in MySQL (many to many relationship)

From Dev

How to make a many to many relationship in core data in the .xcdatamodel

From Dev

How to get data of the middle table in many to many relationship in sequelize

From Dev

How to implementing a many to many relationship with extra columns in Spring Data JPA?

From Dev

How to insert data to tables which is in "has and belongs to many" relationship. Controller and Model generated by scaffold in rails

From Dev

INSERT statement for One to Many relationship

From Dev

Laravel insert in one to many relationship

From Dev

Insert data simultaneously in entity having one to many relationship

From Dev

iOS Core Data to-many relationship insert/fetch

From Dev

Fail to try insert data in a one-to-many relationship with additional fields

From Dev

Sails.js How to insert data into a join table (Many to Many)

From Dev

How To Loop SQL Insert for many data On PHP

From Dev

Saving data many-to-many relationship

From Dev

Split Table into many to many relationship: Data Migration

Related Related

  1. 1

    How to insert and fetch to-many relationship entities in core data

  2. 2

    Doctrine + Zend Framework 2: Insert array of data in a many to many relationship

  3. 3

    coreData insert to to many relationship

  4. 4

    coreData insert to to many relationship

  5. 5

    How to Insert, Update, Delete in a one to many relationship?

  6. 6

    MySQL - How to insert into table that has many-to-many relationship

  7. 7

    How to insert into associative table in many to many relationship by Hibernate?

  8. 8

    how to flatten many to many relationship

  9. 9

    how to query a many to many relationship?

  10. 10

    How to save many to many relationship?

  11. 11

    how to flatten many to many relationship

  12. 12

    Bulk Insert Many-to-Many Relationship

  13. 13

    INSERT/DELETE examples in a many-to-many relationship

  14. 14

    PostgreSQL insert array many-to-many relationship

  15. 15

    How to retrieve data from many to many relationship in Django

  16. 16

    How to query a pivot table data in MySQL (many to many relationship)

  17. 17

    How to make a many to many relationship in core data in the .xcdatamodel

  18. 18

    How to get data of the middle table in many to many relationship in sequelize

  19. 19

    How to implementing a many to many relationship with extra columns in Spring Data JPA?

  20. 20

    How to insert data to tables which is in "has and belongs to many" relationship. Controller and Model generated by scaffold in rails

  21. 21

    INSERT statement for One to Many relationship

  22. 22

    Laravel insert in one to many relationship

  23. 23

    Insert data simultaneously in entity having one to many relationship

  24. 24

    iOS Core Data to-many relationship insert/fetch

  25. 25

    Fail to try insert data in a one-to-many relationship with additional fields

  26. 26

    Sails.js How to insert data into a join table (Many to Many)

  27. 27

    How To Loop SQL Insert for many data On PHP

  28. 28

    Saving data many-to-many relationship

  29. 29

    Split Table into many to many relationship: Data Migration

HotTag

Archive