【问题标题】:Add or Update a Record?添加或更新记录?
【发布时间】: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


【解决方案1】:

您需要检查数据库中您尝试添加/更新的记录。如果查找返回 null,则表示它在数据库中不存在。如果是这样,您可以修改您查找的记录并调用 db.SaveChanges() 以持久保存您对数据库所做的更改。

编辑:

int id = Convert.ToInt32(harmonyAttributeID);
var existingEntry = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == id);

【讨论】:

  • 你能告诉我代码吗?如何进行查找?
【解决方案2】:

确定添加或更新的一种常见方法是简单地查看标识符字段并设置适当的状态。

using System.Data;

SelectedHarmonyAttribute attribute;

using (var db = new YourDbContext())
{
    db.Entry(attribute).State = attribute.HarmonyAttribute_ID == 0 ? EntityState.Added : EntityState.Modified;

    db.SaveChanges();
}

【讨论】:

    【解决方案3】:

    您可以导入 System.Data.Entity.Migrations 命名空间并使用 AddOrUpdate 扩展方法:

    db.SelectedHarmonyAttributes.AddOrUpdate(attribute);
    db.SaveChanges();
    

    编辑: 我假设 SelectedHarmonyAttributes 的类型是 DbSet

    编辑2: 这样做的唯一缺点(您可能不关心)是您的实体不对其自己的状态更改负责。这意味着您可以将实体的任何属性更新为无效的内容,您可能希望在实体本身内部对其进行验证,或者进行一些您总是希望在更新时进行的其他处理。如果您担心这些事情,您应该在实体上添加一个公共更新方法,并首先检查它在数据库中是否存在。例如:

    var attribute = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == harmonyAttributeID);
    
    if (attribute != null)
    {
        attribute.Update(viewModel.ItemCaptionText, viewModel.Isselected, i++); 
    }
    else
    {
        attribute = new Attribute(viewModel.ItemCaptionText, viewModel.Isselected);
        db.SelectedHarmonyAttributes.Add(attribute);
    }
    
    db.SaveChanges();
    

    您的更新方法可能类似于:

    public void Update(string customLabel, bool isVisible, int orderNumber)
    {
        if (!MyValidationMethod())
        {
            throw new MyCustomException();
        }
    
        CustomLabel = customLabel;
        IsVisible = isVisible; 
        OrderNumber = orderNumber;
    
        PerformMyAdditionalProcessingThatIAlwaysWantToHappen();
    }
    

    然后将所有实体的属性设为公共“get”但受保护“set”,这样它们就无法从实体本身外部更新。这可能有点偏离,但使用 AddOrUpdate 方法会假设您不想控制更新发生的方式并保护您的域实体不进入无效状态等。希望这会有所帮助!

    【讨论】:

    • 小心。这不是它的设计目的......thedatafarm.com/data-access/…
    • 是的,我在发布答案后意识到它确实有其缺点。我已经编辑了我的答案以进一步限定它,但如果了解缺点并且知道要比较的主键,它可能是合适的。 (在这个例子中,HarmonyAttribute_ID 是主键)
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多