1

I have the following code:

BudgetLineItem actualLi = new BudgetLineItem();
actualLi.YearId = be.lu_FiscalYear.Where(t => t.Year == actualYear).Select(t => t.Id).First();
actualLi.TypeId = be.lu_Type.Where(t => t.Name == "Actual").Select(t => t.id).First();
actualLi.DeptId = be.lu_Department.Where(t => t.Name == DeptName).Select(t => t.ID).First();
actualLi.LineItemId = be.lu_LineItem.Where(t => t.Name == revenueType).Select(t => t.id).First();
actualLi.Amount = actualAmount;
be.AddToBudgetLineItems(actualLi);
be.SaveChanges();

Which creates an object with exactly what I want to insert in the database. But when I try to save this record I get the error:

Entities in 'xxxx' participate in the 'xxxx' relationship. 0 related 'xxxx' were found. 1 '' is expected.

My BudgetLineItem table has a foreign key relationship with a table called lu_Department which is what the error references.

I found this question which seems to offer a solution, but it seems overly complex for what I am trying to do.

Is my best option the solution provided in the question I linked to? If so, why does EF make this so complicated?

Community
  • 1
  • 1
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

1 Answers1

0
BudgetLineItem actualLi = new BudgetLineItem();
actualLi.YearId = be.lu_FiscalYear.FirstOrDefault(t => t.Year == actualYear);
actualLi.TypeId = be.lu_Type.FirstOrDefault(t => t.Name == "Actual");
actualLi.Dept = be.lu_Department.FirstOrDefault(t => t.Name == DeptName)
actualLi.LineItemId = be.lu_LineItem.FirstOrDefault(t => t.Name == revenueType)
actualLi.Amount = actualAmount;
be.AddToBudgetLineItems(actualLi);
be.SaveChanges();

I would suggest to attach the entity directly rather than with the "ID". This will solve the problem as your DB context will be dealing with the entity relations for which it has been designed

If All those Id's are FK's change them to assignment of entity like for lu_Department

Apurav
  • 198
  • 1
  • 11