创建了重复记录,在Entity Framework 6中保存对db的更改

时间:2013-11-13 07:03:24

标签: c# asp.net-mvc entity-framework

在Visual Studio 2013 web express中使用MVC 5,EF 6.01和Identity。

我认为这是一个简单的任务,即添加历史表来跟踪定价的变化。对于父记录的每次保存,正在创建两个子历史记录,但不确定原因。我尝试了下面的方法,也没有使用集合(单独更新的隔离历史表)。还尝试更改控制器中的事件顺序。

 private AppDb db = new AppDb();
 private UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());

 public class Threshold
 {
    public int ThresholdId { get; set; }
    public string ItemId { get; set; }
    public string OfficeCode { get; set; }
    public string Unit { get; set; }
    public string Type { get; set; }
    public string Color { get; set; }
    public string Frequency { get; set; }
    public decimal Price { get; set; }
    public decimal OldPrice { get; set; }
    public int? Volume { get; set; }
    public int? Sort { get; set; }
    public DateTime? DateModified { get; set; }
    public virtual ICollection<Threshold_History> Threshold_History { get; set; }
}

public class Threshold_History
{
    public int Threshold_HistoryId { get; set; }
    public int ThresholdId { get; set; }
    public decimal PriceFrom { get; set; }
    public decimal PriceTo { get; set; }
    public DateTime DateCreated { get; set; }
    public string UserId {get; set;}
    public virtual Threshold Threshold { get; set; }
}

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult  Edit([Bind(Include="ThresholdId,ItemId,OfficeCode,Unit,Type,Color,Frequency,Price,Volume,Sort,OldPrice")] Threshold threshold)
{
    if (ModelState.IsValid)
    {
        db.Entry(threshold).State = EntityState.Modified;

        //update history table
        Threshold_History hist = new Threshold_History();
        List<Threshold_History> histories = new List<Threshold_History>();
        hist.ThresholdId  = threshold.ThresholdId;
        hist.PriceFrom = threshold.OldPrice;
        hist.PriceTo = threshold.Price;
        hist.DateCreated =  DateTime.Now;
        hist.UserId = User.Identity.GetUserId();

        histories.Add(hist);

        threshold.DateModified = DateTime.Now;
        threshold.Threshold_History = histories;

        db.SaveChanges();

        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
    }
}

一个注意事项:调试器中的每个Step Over都必须单击两次。它几乎就像有两个代码同时运行的实例。其他模块和类在单步执行时可正常工作。

编辑以添加如何调用Edit。它来自模态对话框中的ajax调用:

//modal functions
 function editItem(e){
 e.preventDefault(); 
 $('#dialogContent').load(this.href, function () {
    $('#dialogDiv').modal({
        backdrop: 'static',
        keyboard: true
    }, 'show');
    bindForm(this);
});
return false;
};

function bindForm(dialog) {
$('form', dialog).submit(function () {

    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (result) {
            if (result.success) {
                $('#dialogDiv').modal('hide');
                 loadTab(tabRef);
            } else {
                $('#dialogContent').html(result);
                $('#dialogDiv').modal({
                    backdrop: 'static',
                    keyboard: true
                }, 'show');
                bindForm();
            }
        },
        error: function (requestObject, error, errorThrown) {
            $('#modalError').html("<br><p>" + errorThrown + "</p> ");
        }
    });
    return false;
});
}

function validateModal() {
var form = $(".modal-form");
$.validator.unobtrusive.parse(form);
if (form.valid()) {
    form.submit();
}
}

1 个答案:

答案 0 :(得分:2)

您是否从表单上的提交按钮调用validateModal()?我没有看到任何preventDefaultreturn false,因此提交按钮可能会调用validateModal,这会导致表单被发布,并且提交按钮仍然执行它的默认功能:张贴表格。这可以解释重复的电话。

如果您自己处理提交,则应将提交按钮的类型设置为“按钮”,以防止其自动提交。