When using Entity Framework 4, how do you create a single entity from a stored procedure?
-
1I added my answer, but may have misunderstood. Do you want to retrieve an entity from the database using a stored procedure, or create a new entity and save it to the database using a stored procedure?Jeff Ogata– Jeff Ogata2010-12-01 21:22:05 +00:00Commented Dec 1, 2010 at 21:22
-
Yeah the main thing is that I don't want the entities having access to the table outside of procedures.Achilles– Achilles2010-12-01 21:35:24 +00:00Commented Dec 1, 2010 at 21:35
-
typically, I'd create a view over every relevant table (which e.g. shows only the "valid" or "non-deleted" entries), and use stored procs for INSERT, UPDATE, DELETE (only logical - only mark for deletion) operations on those entities. Well supported in EF4marc_s– marc_s2010-12-01 22:17:22 +00:00Commented Dec 1, 2010 at 22:17
1 Answer
After you add the stored procedure to the model, from the Model Browser right-click the stored procedure under the Store node and select 'Add Function Import'. In that dialog, indicate what entity should be created:

You can then use that stored procedure like this:
Artist a = ctx.SelectArtist(id).SingleOrDefault();
Edit
Based on the comments, it sounds like you want to use stored procedures to perform inserts, updates, and deletes. If you right-click on the entity in the model browser and select 'Stored Procedure Mapping', you'll get a window that lets you specify which stored procedures to use. MSDN has a walkthrough on how to do this.
HTH