为什么通过实体框架的SaveChanges会在通过dbContext添加一条记录时影响更多记录

时间:2015-06-25 16:59:35

标签: c# wpf entity-framework sqlite

我在ViewModelLocator中创建了如下服务:

 var context = new DbEntities();
 SimpleIoc.Default.Register<IPaymentLogService>(() => new PaymentLogService(context));


public PaymentLogService(installmentsEntities context)
    {
        _context = context;
        _paymentLogRepository = new PaymentLogRepository(context);
    }

我的存储库创建如下:

public PaymentLogRepository(DbEntities context)         {             _context = context;         }

通过实体框架添加行时,如下所示:

public int Add(PaymentLog entity)
{
    _context.PaymentLogs.Add(entity);
    var affectedRows = _context.SaveChanges();

    return numberOfAddedItems;
}

以上功能删除记录。 affectedRows = 2PaymentLogs被引用到另一个对象,并且首先没有添加新对象,而且还引用了LoanAgreement行从数据库中删除。

为什么?

准备添加的新记录如下传达:

 var result = new PaymentLog() { PayedAmount = newPayment.PaymentAmout, LoanAgreementID = newPayment.LoanID };

PaymentLog对象引用LoanAgreement。如上所示,在将其传递给功能之前,我仅设置参考的FK ID。我预计会添加新记录。没有添加任何记录。一个被删除,saveChangs返回值= 2.

CREATE TABLE "PaymentLogs" ("ID" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL,"LoanAgreementID" INTEGER NOT NULL,
"PayedAmount" DECIMAL NOT NULL,

 FOREIGN KEY ([LoanAgreementID]) REFERENCES [LoanAgreements] ([ID]) 
        ON DELETE NO ACTION ON UPDATE NO ACTION)

1 个答案:

答案 0 :(得分:0)

Thanks to your remarks "sstan" I added logging context info: _context.Database.Log = s => Debug.WriteLine(s); It occured that following update was performed. UPDATE [LoanAgreements] SET [LoanTypeID] = @p0 WHERE ([ID] = @p1); -- @p0: '0' (Type = Int64) -- @p1: '7' (Type = Int64) Above update was done unnecessary. When user adds new LoanAgreement from WPF UI then in case it succeded I resets UI like this via binding: private ProductTypeDto _productType; public ProductTypeDto ProductType { get { return _productType; } set { _productType = value; //this caused unwanted updated: _loanAgreement.LoanTypeID = _productType.ID; } } Then every next action tried to perform what was done in above setter; It occured this to be bad idea to bind directly to db object which is known to context. Maybe another problem is related to _context itself since it is created once and lives all the time.