jeudi 25 juin 2015

Why adding row via Entity Framework ORM removes parent record

I have service created as follows:

 var context = new DbEntities();

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


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

I have repository created as follows:

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

When adding row via Entity Framework like this:

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

    return numberOfAddedItems;
}

Above function removes records. affectedRows = 2. PaymentLogs is referenced to another object and firstly new object is not added and moreover referenced LoanAgreement row is removed from database.

WHY?

New record to be added is conveyed like this:

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

PaymentLog object has a reference to LoanAgreement. As seen above, before conveying it to function I only set referenced FK ID. I Expected new record to be added. No record was added. One was removed and saveChangs returned value = 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)

Aucun commentaire:

Enregistrer un commentaire