1

在我们的 SQL 数据库中,我们有一个带有复合键的表,其中包含我们需要不时更新的字段。我的理解是,由于我们使用的是实体框架,因此我需要先从数据库中删除记录,然后再将行添加回表中。

下面是我创建的用于处理“更新”的简单方法,因为有许多方法可以执行此操作。但是,一旦在我得到以下.SaveChanges()方法后调用该方法:.RemoveDbUpdateConcurrencyException

Store update, insert, or delete statement affected an unexpected number of 
rows (0). Entities may have been modified or deleted since entities were loaded. 
Refresh ObjectStateManager entries.

不确定我做错了什么,因为我正在尝试删除记录,然后执行更新,然后重新添加记录。

这是调用删除/编辑方法的方法。调用此方法时,记录尚未以任何方式更改形状或形式。

    private static void ProcessAllChanges(ZipCodeIndex information, ZipCodeTerritory zipToUpdate)
    {
        try
        {
            RemoveRecord(zipToUpdate);

            if (!string.IsNullOrWhiteSpace(information.newTerritory)) zipToUpdate.IndDistrnId = information.newTerritory;
            if (!string.IsNullOrWhiteSpace(information.newStateCode)) zipToUpdate.StateCode = information.newStateCode;
            if (!string.IsNullOrWhiteSpace(information.newDescription)) zipToUpdate.DrmTerrDesc = information.newDescription;
            if (!string.IsNullOrWhiteSpace(information.newChannelCode)) zipToUpdate.ChannelCode = information.newChannelCode;
            if (zipToUpdate.EndDate == DateTime.MinValue) zipToUpdate.EndDate = DateTime.MaxValue;

            EditRecord(zipToUpdate);
            _updated++;   
        }
        catch (DbEntityValidationException dbEx)
        {
            _msg += "Error during update; ";
            EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |EX| " + dbEx.Message);
        }
        catch (Exception ex)
        {
            _msg += "Error during update; ";
            EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |MESSAGE| " + ex.Message);
        }
    }

这是两个被调用的辅助方法

    public static void RemoveRecord(ZipCodeTerritory zipCode)
    {
        _db = new AgentResources();
        _db.ZipCodeTerritory.Attach(zipCode);
        _db.ZipCodeTerritory.Remove(zipCode);
        _db.SaveChanges();
    }

    public static void EditRecord(ZipCodeTerritory zipCode)
    {
        _db = new AgentResources();
        _db.ZipCodeTerritory.Add(zipCode);
        _db.SaveChanges();
    }

编辑

根据下面的一些评论,我尝试创建上下文对象的单独实例,但是使用此方法我收到了相同的错误:

    public static void RemoveRecord(ZipCodeTerritory zipCode)
    {
        using (AgentResources deleteMe = new AgentResources())
        {
            deleteMe.ZipCodeTerritory.Attach(zipCode);
            deleteMe.ZipCodeTerritory.Remove(zipCode);
            deleteMe.SaveChanges();                
        }
    }

第二次编辑

这是调用ProcessAllChanges我上面发布的方法的最上面的方法。

    public static string TerritoryOnly(ZipCodeIndex updateZip)
    {
        if (!string.IsNullOrWhiteSpace(updateZip.newEffectiveDate) || !string.IsNullOrWhiteSpace(updateZip.newEndDate))
        {
            return "Neither effective or end date can be present if updating Territory Code only; ";
        }

        RefreshProperties();

        foreach (var zipCode in updateZip.displayForPaging.Where(x => x.Update))
        {
            ProcessAllChanges(updateZip, zipCode);
        }

        _msg += _updated + " record(s) updated; ";

        return _msg;
    }

第三次编辑

AgentResources这里的每个请求是我们的DbContext对象的完整类定义

namespace Monet.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class AgentResources : DbContext
    {
        public AgentResources()
            : base("name=AgentResources")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<AgentContEd> AgentContEd { get; set; }
        public DbSet<ContEdCourse> ContEdCourse { get; set; }
        public DbSet<Course> Course { get; set; }
        public DbSet<CourseToProduct> CourseToProduct { get; set; }
        public DbSet<Product> Product { get; set; }
        public DbSet<ProcessControl> ProcessControl { get; set; }
        public DbSet<AgentIdToTradingPartner> AgentIdToTradingPartner { get; set; }
        public DbSet<TradingPartner> TradingPartner { get; set; }
        public DbSet<Notes> Notes { get; set; }
        public DbSet<CourseMaterials> CourseMaterials { get; set; }
        public DbSet<TransactionLog> TransactionLog { get; set; }
        public DbSet<Agent> Agent { get; set; }
        public DbSet<AgentIdentification> AgentIdentification { get; set; }
        public DbSet<BatchDashboard> BatchDashboard { get; set; }
        public DbSet<BatchPrograms> BatchPrograms { get; set; }
        public DbSet<FollowUpItems> FollowUpItems { get; set; }
        public DbSet<sysdiagrams> sysdiagrams { get; set; }
        public DbSet<AgentProductTraining> AgentProductTraining { get; set; }
        public DbSet<Channel> Channel { get; set; }
        public DbSet<RelationshipCodes> RelationshipCodes { get; set; }
        public DbSet<DropDownValues> DropDownValues { get; set; }
        public DbSet<QueueUpdates> QueueUpdates { get; set; }
        public DbSet<MarketingLookup> MarketingLookup { get; set; }
        public DbSet<TransmissionHistory> TransmissionHistory { get; set; }
        public DbSet<AgentTransmission> AgentTransmission { get; set; }
        public DbSet<ZipCodeTerritory> ZipCodeTerritory { get; set; }
    }
}

这是ZipCodeTerritory课程

public partial class ZipCodeTerritory
{
    public string ChannelCode { get; set; } //Composite key field
    public string DrmTerrDesc { get; set; }
    public string IndDistrnId { get; set; }
    public string StateCode { get; set; } //Composite key field
    public string ZipCode { get; set; } //Composite key field
    public System.DateTime? DisplayEndDate { get; set; }
    public System.DateTime EndDate { get; set; } //Composite key field
    public System.DateTime EffectiveDate { get; set; } 
    public string LastUpdateId { get; set; }
    public Nullable<System.DateTime> LastUpdateDate { get; set; }
}
4

1 回答 1

1

尝试这个 :

public static void RemoveRecord(ZipCodeTerritory zipCode)
{
    using(var _newdb = new AgentResources())
    {
        ZipCodeTerritory zipCodeRemove = new ZipCodeTerritory();
        zipCodeRemove.channelCode = zipCode.channelCode;
        zipCodeRemove.stateCode = zipCode.stateCode;
        zipCodeRemove.zipCode= zipCode.zipCode;
        zipCodeRemove.endDate = zipCode.endDate;

        _newdb.ZipCodeTerritory.Attach(zipCodeRemove);
        _newdb.ZipCodeTerritory.Remove(zipCodeRemove);
        //((IObjectContextAdapter)_newdb).ObjectContext.Refresh(
                                                    // RefreshMode.ClientWins
                                                    //, zipCode);
        _newdb.SaveChanges();
    }
}
于 2013-10-30T22:08:18.193 回答