I'm using EF6 with code first migrations to create my database. I made a mistake with my models, but am struggling to understand why this is happening.
I have two tables
[TrackChanges]
public class Loan
{
public long Id { get; set; }
....
public virtual LoanAddress LoanAddress { get; set; }
public Loan() {
LoanAddress = new LoanAddress();
}
}
[TrackChanges]
public class LoanAddress
{
public long Id { get; set; }
...
}
When I create a new Loan with a new LoanAddress, it usually creates two LoanAddresses. One's assigned to the Loan and the other is an orphan.
public async Task<IHttpActionResult> Create(LoanViewModel l)
{
try
{
Loan loan = new Loan
{
//LoanAddress = new LoanAddress(),
...
};
dbContext.Loan.Add(loan);
await dbContext.SaveChangesAsync(currentUserName);
return Ok(loan.Id);
}
catch (Exception ex)
{
....
}
}
If I debug and step through, dbContext.LoanAddress has two entries in Local.
What's really confusing me is this doesn't happen when
- The database is empty (it creates one record)
- Sometimes when I debug the code and watch LoanAddress it acts fine
- I do something similar using the database seed method. It behaves fine here
One thing that doesn't help is LoanAddress not having a reference back to Loan. That was a mistake (is this one to many without?), but using code-first migrations struggles to fix it. I have live data in the table, and am unsure if I can fix that.
Otherwise, creates and updates work, just that creating Loans creates orphaned rows.