Entity Framework: saving a record with FK values ​​and NOT searching for relationships

I have an Expenses table that contains the FK value in the ExpenseType table. Right now, if I want to save a new expense, I first get the value int FK, look at the ExpenseType table and assign the object to the expense object. For example:

//create new expense
var e = new Expense();

//lookup the associated expense type
var et = context.ExpenseTypeSet.First(e -> e.expenseTypeID == 10);

//set field values
e.expenseName = "Some name";
e.expenseType = et;

//save
context.Save();

Is there a way to create / insert a record without first requesting to the FK table? The search is unnecessary and causes extra database hits. I already know the FK ID ... so is there a way to just set the identifier and let it be happy?

Thanks in advance -

+3
source share
1 answer

You can also use EntityReference:

e.expenseTypeReference.EntityKey 
   = new EntityKey("MyContainer.expenseTypeSet", "expenseTypeID", 10);

, :

, Tip 7, FK. , , .

+4

Source: https://habr.com/ru/post/1707699/


All Articles