Reputation:
I Create Two class in Models folder Like this:
Material.cs:
public class Material
{
public int MaterialId { get; set; }
public string Name { get; set; }
public virtual ICollection<Project> Project { get; set; }
}
Project.cs:
public class Project
{
[Key]
public int ProjectId { get; set; }
[Required]
public string Name { get; set; }
public DateTime Date { get; set; }
public ICollection<Material> Material { get; set; }
}
Entity framework code first generate a new table with name MaterialProjects
in my SQL server database. I use scaffolding to generate Controllers
and Views
.
MaterialProjects
have two Columns like this:
Material_MaterialId
Project_ProjectId
In 1st step I add a new project record into Projects
table.
In 2nd step I add a new material record into Materials
table.
My question is: How can I add a record to MaterialProjects
table. I cant access this entity in my code.
UPDATE: Have I do this in Materials controller create Action method?
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "MaterialId,Name,")] Material material)
{
if (ModelState.IsValid)
{
db.Materials.Add(material);
//what to do here
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(material);
}
Upvotes: 1
Views: 1346
Reputation: 1977
you dont have to add in that table it will be done by EF automaticaly . The only thing you need to do id to add your entities correctly and the junction table will be filled by EF you dont have to do that .
In controller you can do like this .I tested with console application.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "MaterialId,Name,")] Material material)
{
if (ModelState.IsValid)
{
using (var ctx = new SampleDbContext())
{
-- here context is the DBCOntext class of your application
--var mat = new Material
--{
-- Name = "A",
-- Project = new List<Project> {new Project {Name = "P1", Date = DateTime.Now}}
--};
ctx.Materials.Add(material);
await db.SaveChangesAsync();
}
return RedirectToAction("Index");
}
return View(material);
}
Upvotes: 1
Reputation: 6440
EF automatically handles the Many-Many junction tables.In your case, say you want to insert a new Project
with two new Material
entities. You can do this by assigning the materials collection to the Material
collection of the new Project
entity. EF will inset a new Project and two new materials and will automatically populate the junction table as well
Updating after OP updates the question Hoping that you have already have the Project entity inserted (say, the id of that project is 100). So while adding new Material entity:
var proj = context.Projects.Find (100);
newMaterialObject.Projects.Add (proj);
context.SaveChanges();
Upvotes: 0