D
D
Di-Roll2017-01-17 17:35:40
.NET
Di-Roll, 2017-01-17 17:35:40

How to map stored procedures in Entity Framework?

To interact with the database, stored procedures must be used, there is no access to tables.
Using the method, MapToStoredProceduresI set up DbSet'ыto use stored procedures for inserting, updating and deleting data.
And what about sampling?
It can be used Context.Database.SqlQueryto execute a stored procedure to select data,
but then an error occurs when deleting a record (you have to use the method Attach):

Context.Table.Attach(item);
Context.Table.Remove(item);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kuznetsov, 2017-01-18
@Di-Roll

For sampling, I would advise you to map on table-values ​​functions, because they are optimized when fetching (for example, if you apply where after a call in .NET), unlike procedures that pull out the entire selection. Again, this option will allow you to work with them as with IQueryable, which is a definite plus.
If you have EDMX, then these functions will be mapped automatically by the wizard. If Code First then you need https://github.com/moozzyk/CodeFirstFunctions , the Nuget package is called EntityFramework.CodeFirstStoreFunctions.
We have been using (and are using this approach) since 2013 - during this time there were no problems with it. Another point, this only works for MSSQL, if you use something else, then this option will not work.
For example, in my case, the database suddenly became PostgreSQL, and I did it a little differently. I mapped the selection onto a view, where I multiplied JOINs to get all sorts of options (in my case, this is a bunch of entity-resources-resource_language:

CREATE OR REPLACE VIEW public.v_companies AS 
 SELECT c.id,
    c.isdeleted,
    c.hversion,
    c.modifydate,
    c.modifierid,
    l.id AS languageid,
        CASE
            WHEN cr.id IS NOT NULL THEN cr.name
            ELSE cr_fb.name
        END AS name
   FROM companies c
     JOIN languages l ON true --- тада!
     LEFT JOIN company_resources cr ON c.id = cr.companyid AND cr.languageid = l.id
     LEFT JOIN company_resources cr_fb ON c.id = cr_fb.companyid AND cr_fb.languageid = (( SELECT crx.languageid
           FROM company_resources crx
          WHERE c.id = crx.companyid
         LIMIT 1))
  ORDER BY c.id, (
        CASE
            WHEN cr.name IS NOT NULL THEN 0
            ELSE 1
        END)

And I made an extension-method to get the model of this View, where I gave the CurrentLanguageId and filtered on it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question