C# – Mapping select stored procedures in entity framework

asp.netcentity-frameworkstored-procedures

My scenario
I'm using Visual Studio 2010 with Entity Framework 4.1
I have a legacy database with many tables and many stored procedures.
I'm writing an ASP.NET C# program using MVC 3

I have adopted the 'database first' design using ADO.NET DbContext so I have an edmx with all the models and associations and navigation properties nicely set up.
I can map the insert, update, delete procedures to the relevant models.
I've used 'Function Import' to import other stored procedures.
However, I can't find a way to map my Select procedures to select actions (select by id, select list, select by filter etc).

EF seems to use lazy loading so what I want to happen is when an object fetches its child objects it uses the stored procedures already written.
(The select procedures take into account an 'IsDeleted' flag, and use the 'ORDER BY' clause, amongst others)

I see from this article
http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx
that Linq to SQL allows drag and drop of SPs, which sounds, more or less, exactly what I want.

I've also come across the term DefiningQuery.
http://msdn.microsoft.com/en-us/library/cc982038.aspx
Is this what I want? I don't like the note 'Any changes made to the storage model, including defining queries, will be overwritten when you run the Update Model Wizard.'

In summary, what I want to happen is when an object fetches its child objects it uses my stored procedures.

Can I achieve my goal using Entity Framework?
Have I missed something obvious?

Or should I try to be really clever and modify the db Entity T4 template, so that, for example, my generated Address model has this property:

public virtual ICollection<AddressLine> AddressLines { 
    get{
        DBWrapper _db = new DBWrapper();
        return _db.GetAddressLines(AddressID);
    } 
    set{}; 
}

where GetAddressLines is custom function that calls a function import and does the neccessary conversions.

Best Answer

It is not possible. You can import your stored procedures as function imports and manually execute them but you cannot replace queries generated by EF with custom stored procedures.

Related Topic