Appendix B. Entity Framework tips and tricks
Mastering Entity Framework doesn’t only mean knowing its set of APIs and their internal behavior. It also means finding the best ways to use it and to simplify development. This appendix is all about that.
We won’t cover a specific subject here; we’ll touch on various subjects, offering tips and tricks that couldn’t be included in previous chapters. Here you’ll find a set of classes and extension methods that let you write less code, making that code more readable and easier to maintain.
You’ll read about an extension method for simplifying the process of attaching entities, you’ll learn how to perform specific actions once an entity is persisted on the database, and you’ll discover how to perform full-text searches. You’ll also see how to transform some string-based methods to lambda-based methods (such as Include and SetModifiedProperty), and much more.
Let’s start with a smarter way to attach entities to the context.
In chapter 12, you created an extension method that, using EDM and a bit of reflection, adds or attaches an entity to the context depending on the value of the entity’s key property. When the entity is attached, it goes to the Unchanged state, and you then need to modify a property or use context or state manager methods to mark it as Modified or Deleted.
If you know what the entity state should be after it’s attached, wouldn’t it be better to set it immediately in the same call?