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 ??
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.
Comments