When using Entity Framework, should I set the navigation property or foreign key property, when setting the FK?

c# entity-framework entity-framework-core orm

Question

I have some code that looks like this:

var customer = dbcontext.Customers.Find(1);

var order = new Order();
order.CustomerId = customer.Id;

dbcontext.Orders.Add(order);
dbcontext.SaveChanges();

Is it best practice to this or set the relationship by setting the navigation property:

var customer = dbcontext.Customers.Find(1);

var order = new Order();
order.Customer = customer; //Set navigation prop as opposed to FK field

dbcontext.Orders.Add(order);    
dbcontext.SaveChanges();

What approach is considered best practice or preferred?

1
0
2/20/2020 10:49:12 PM

Popular Answer

Are you worried about performance?

A) No: if you are not then you shouldn't worry about this and always use navigation properties for readability.

B) Yes: Then you should have queried the customer with a .Select(c => c.id) to begin with and still only use navigation properties. In this case it is clear you will not be updating any other field of Customer because you are comparing it to only setting the FK.

var customer = dbcontext.Customers
                        .Find(1)
                        .Select(b => new Customer { Id = b.Id } );

var order = new Order();
order.Customer = customer; //Set navigation prop as opposed to FK field

dbcontext.Orders.Add(order);    
dbcontext.SaveChanges();

C) Yes very much: In this simplified example you gave, it's pointless to query the Customer with it's PK to then only use the PK. You already have all the info you need, you could have set it directly in the Order. However we will have to attach it manually or efcore will try to create a Customer that already exists.

var order = new Order();
order.Customer = new Customer { Id = 1 };
dbcontext.Attach<Customer>(order.Customer); 

dbcontext.Orders.Add(order);    
dbcontext.SaveChanges();
0
2/21/2020 9:05:46 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow