Question

When using EF Code First to generate a database, you declare the DB sets within the DbContext class for example..

public DbSet< ProductOption > ProductOptions { get; set; }

Now from the reading I have been doing, if you have a related entity in the type ProductOptions you do not need to declare it as EF will look at the dependents and use them to create the required DB tables.

My question is this: Is this recommend practice? And if so how do you then access the related type in code as it does not exist as a data set.

Also this auto-discover feature of EF, does it do it in both directions, i.e if you declare a db set that does not have any related entities inside it, but it is an entity that is in some other entity, will EF find it?

Any clarification is welcome. Thanks

EDIT

Example of what I am saying in terms of not being able to access the Types that are auto discovered is when your seeding data.

Was it helpful?

Solution

You actually do have access to the types without declaring DbSets inside your context class. Inside your context initialization class under the Seed method you can access any of your entities using the yourContext.Set().Add(theObject). This way you do not need to have DBSet properties inside your context class. I am not sure what version of EF you are using or if your are using an initialization class for seeding the data. Regardless, you can still use the .Set().Add, to seed the data.

With regards to the question will EF find the non related entities. Like you said, as long as an object is a property of an entity EF should create a table for it. As long as in code first you declare a mapping for any entity, it should create it and any child entities that may or may not have mappings for themselves. I'd have to see how you are declaring your context and mappings to be sure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top