Link to home
Start Free TrialLog in
Avatar of bkadirbeyoglu
bkadirbeyogluFlag for Türkiye

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:

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

Open in new window


 
public class Category
    {
        public int CategoryID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }

        public ICollection<ServiceProvider> ServiceProviders { get; set; }
    }

Open in new window



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

Open in new window

Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Would try this:

for each var cat in db.Categories.Where(d => d.CategoryID == id)
                    newSP.Categories.Add(cat);
Avatar of bkadirbeyoglu

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.
ASKER CERTIFIED SOLUTION
Avatar of bkadirbeyoglu
bkadirbeyoglu
Flag of Türkiye image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I posted the link where my problem was solved.