Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I disable automatic relationships in Entity Framework Code First?

I noticed that Entity Framework still has a lot of "automagical" features in their latest release. As always, this is a truly double-edged sword.

Specifically, I'm using the OnModelBuilder event to create my model on the fly in code using the fluentAPI (http://msdn.microsoft.com/en-us/library/hh295844(v=vs.103).aspx). I have a large set of entities, and they don't all comply with the Microsoft "standards". For example, my ID columns are named Person_id instead of PersonId. As such, Entity doesn't always auto-detect the primary key on a table, or at least, it doesn't seem to do so.

I don't mind being explicit when building the model, but what does trouble me is that I'm not always sure what properties and relationships Entity will auto-detect and which ones it will erroneously ignore or misidentify. Since most of my entities also have a partial class with helper methods and properties (stuff to handle enums, etc), I greatly fear that someday Entity will auto create mappings between things which shouldn't be mapped (the failure could be Entity or some unsuspecting programmer).

Is there a way I can disable Entity's auto-relationship-hookup feature so that I can be 100% explicit in my OnModelBuilder method? Or, at minimum, how can I know when I need to add extra mapping details (like needing to declare a field optional, or when a specific navigation property won't be autodetected)?

Thanks!

like image 975
Brett Avatar asked Nov 30 '11 19:11

Brett


2 Answers

The auto-magic is done by conventions inside EF code first. You can remove any of those conventions to turn off some magic or you can remove them all and after that you will have to be 100% explicit in your fluent-API.

like image 58
Ladislav Mrnka Avatar answered Sep 28 '22 09:09

Ladislav Mrnka


Ok, since the removing of conventions does not work, there's a simple way to not-to map all non-configured properties inside EF6.x

The basic is to use separate mapping classes, and after doing the manual maps inside a class, simply call a method, that with reflection will force to ignore all properties that weren't configured.

Here's a link to my gist, where the implementation is. Also added a sample as a comment: https://gist.github.com/hidegh/36d92380c720804dee043fde8a863ecb

like image 22
baHI Avatar answered Sep 28 '22 09:09

baHI