【发布时间】:2014-10-28 01:10:54
【问题描述】:
我在控制器的 POST 方法中有一个带有以下代码的 MVC 应用程序。我正在做一个 EF Add,显然这是不对的。如果它不存在,我希望它添加记录,否则更新。请问我该怎么做?
try
{
AttributeEntities db = new AttributeEntities();
IEnumerable<string> items = viewModel.SelectedAttributes2;
int i = 0;
foreach (var item in items)
{
var temp = item;
// Save it
SelectedHarmonyAttribute attribute = new SelectedHarmonyAttribute();
attribute.CustomLabel = viewModel.ItemCaptionText;
attribute.IsVisible = viewModel.Isselected;
string harmonyAttributeID = item.Substring(1, 1);
// attribute.OrderNumber = Convert.ToInt32(order);
attribute.OrderNumber = i++;
attribute.HarmonyAttribute_ID = Convert.ToInt32(harmonyAttributeID);
db.SelectedHarmonyAttributes.Add(attribute);
db.SaveChanges();
}
}
【问题讨论】:
-
您需要存储您要保存的属性的 ID,检查它是否存在于数据库中。如果是,请更新其属性并保存更改。如果没有,则创建并添加它。
-
查看这篇文章的答案。 [这里][1] [1]:stackoverflow.com/questions/6966207/…
标签: c# asp.net-mvc entity-framework