views:

67

answers:

1

Code:

    public ActionResult Create(Group group)
    {
        if (ModelState.IsValid)
        {
            group.int_CreatedBy = 1;
            group.dtm_CreatedDate = DateTime.Now;
            var Groups = Request["Groups"];
            int GroupId = 0;
            GroupFeature GroupFeature=new GroupFeature();
            foreach (var GroupIdd in Groups)
            {
            //    GroupId = int.Parse(GroupIdd.ToString());


            }
            var Features = Request["Features"];
            int FeatureId = 0;
            int t = 0;
            int ids=0;

            string[] Feature = Features.Split(',').ToArray();
            //foreach (var FeatureIdd in Features)
            for(int i=0; i<Feature.Length; i++)
            {
                if (int.TryParse(Feature[i].ToString(), out ids))
                {

                    GroupFeature.int_GroupId = 35;

                    GroupFeature.int_FeaturesId = ids;
                    if (ids != 0)
                    {
                        GroupFeatureRepository.Add(GroupFeature);
                        GroupFeatureRepository.Save();
                    }
                }

            }




            return RedirectToAction("Details", new { id = group.int_GroupId });

        }
        return View();
    }

I am getting an error here Cannot add an entity that already exists. at this line GroupFeatureRepository.Add(GroupFeature); GroupFeatureRepository.Save();

+2  A: 

This line:

GroupFeature GroupFeature=new GroupFeature();

needs to be inside your for loop, like this:

for(int i=0; i<Feature.Length; i++)
{
  if (int.TryParse(Feature[i].ToString(), out ids))
  {
    GroupFeature GroupFeature=new GroupFeature();

You need to add a new GroupFeature each time(e.g. one not in that collection, which your re-used object already is after the first loop). You can't re-use the same GroupFeature object like that for adding, but moving it inside the loop so you generate a distinct GroupFeature each time will resolve this.

Nick Craver