Entity Framework 6 Refresher: Mapping Files
Entity Framework can determine a lot of things about your model on it’s own, but at some point you need to provide some information about your classes that it has no way of knowing. There are three ways to do this: Attributes, via code in the DbContext itself and in separate mapping files.
Using attributes, we can decorate the class with metadata.
This shows that we use a table name of “HobbyHorse”, that HobbyId
is the primary key and that HobbyName
is required and can be a maximum of 25 characters. This creates the following migration:
We can also configure the Hobby
class in the DbContext:
The migration created from this is identical to the migration created when using attributes.
Finally (and preferably, IMO), we can configure Hobby
in it’s own mapping file.
This mapping file needs to be wired up in the DbContext:
Again, this creates an identical migration.
Leave a Comment