bkadirbeyoglu
asked on
ASP.NET MVC EF Code First Many-to-Many Insert
Hello,
I am using EF Code First approach for my web application. I have two entities, Service Providers and Categories and a many-to-many relationship between them. I managed the lookup table automatically generated by using the following code, but could not manage to insert into the lookup table. I'm getting a null reference error when using the following code. I am looking forward to hearing a solution:
I am using EF Code First approach for my web application. I have two entities, Service Providers and Categories and a many-to-many relationship between them. I managed the lookup table automatically generated by using the following code, but could not manage to insert into the lookup table. I'm getting a null reference error when using the following code. I am looking forward to hearing a solution:
In ServiceProvidersController:
[AcceptVerbs("POST")]
public ActionResult Create(ServiceProvider newSP)
{
if (ModelState.IsValid)
{
var categoryId = Request["CategoryID"];
var catIds = categoryId.Split(',');
foreach (var catId in catIds)
{
int id = int.Parse(catId);
Category category = db.Categories.SingleOrDefault(d => d.CategoryID == id);
newSP.Categories.Add(category);
}
db.ServiceProviders.Add(newSP);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
public class Category
{
public int CategoryID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public ICollection<ServiceProvider> ServiceProviders { get; set; }
}
public class ServiceProvider
{
public int ServiceProviderID { get; set; }
[Required]
public string Title { get; set; }
public string Telephone { get; set; }
public string Fax { get; set; }
public string Address { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
ASKER
ged325, thank you, but it did not work either...
http://naspinski.net/post/Getting-started-with-Linq-To-Entities.aspx
See the section about using .Load . . . I think you need to call that before you add.
See the section about using .Load . . . I think you need to call that before you add.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I posted the link where my problem was solved.
for each var cat in db.Categories.Where(d => d.CategoryID == id)
newSP.Categories.Add(cat);