Tuesday, August 23, 2016

Entity Framework - Foreign Key Fields

Something to keep in mind when working with objects that require a foreign key value; Entity Framework can handle this automatically.

If you have an object that requires a foreign key value you might have found yourself calling SaveChanges to save one object to the database to get its ID so you could insert it into another object.

The better way is to use the ForeignKey property on your corresponding property.  The convention is [ForeignKey("ForeignTableNameHere")].  You'll also want to a a public property for the foreign table as well.

Now you can call SaveChanges once at the very end and the foreign key will get set across all the necessary objects.


No comments:

Post a Comment