How do I view the SQL generated by the Entity Framework?

For those using Entity Framework 6 and up, if you want to view the output SQL in Visual Studio (like I did) you have to use the new logging/interception functionality. Adding the following line will spit out the generated SQL (along with additional execution-related details) in the Visual Studio output panel: using (MyDatabaseEntities context = … Read more

How can I retrieve Id of inserted entity using Entity framework? [closed]

It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to ObjectSet and SaveChanges on related ObjectContext. Id will be automatically filled for you: using (var context = new MyContext()) { context.MyEntities.Add(myNewObject); context.SaveChanges(); int id = myNewObject.Id; // Yes it’s here } Entity … Read more

There is already an open DataReader associated with this Command which must be closed first

This can happen if you execute a query while iterating over the results from another query. It is not clear from your example where this happens because the example is not complete. One thing that can cause this is lazy loading triggered when iterating over the results of some query. This can be easily solved … Read more

Fastest Way of Inserting in Entity Framework

To your remark in the comments to your question: “…SavingChanges (for each record)…” That’s the worst thing you can do! Calling SaveChanges() for each record slows bulk inserts extremely down. I would do a few simple tests which will very likely improve the performance: Call SaveChanges() once after ALL records. Call SaveChanges() after for example … Read more

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details [duplicate]

To be honest I don’t know how to check the content of the validation errors. Visual Studio shows me that it’s an array with 8 objects, so 8 validation errors. Actually you should see the errors if you drill into that array in Visual studio during debug. But you can also catch the exception and … Read more