代码:
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();
}
我在这里收到错误无法添加已存在的实体。在这一行GroupFeatureRepository.Add(GroupFeature); GroupFeatureRepository.Save();
答案 0 :(得分:3)
这一行:
GroupFeature GroupFeature=new GroupFeature();
需要在你的for循环中,如下所示:
for(int i=0; i<Feature.Length; i++)
{
if (int.TryParse(Feature[i].ToString(), out ids))
{
GroupFeature GroupFeature=new GroupFeature();
每次都需要添加一个新的GroupFeature
(例如,该集合中的一个不,在第一个循环之后您的重用对象已经存在)。您不能重复使用相同的GroupFeature
对象进行添加,但要在循环中移动它,以便每次生成一个不同的GroupFeature
来解决此问题。