EF and stored procedures to populate entries for an Entity - entity-framework

Is it possible to define an Entity that is not mapped to a table in database and to use a stored procedure to return the entries?
I found that I can use "Ignore" so the table in database is not created for an Entity, but how can I set a stored procedure to populate data for this entity?
Note: I am using code first.
Thanks.

You could create a normal model class that's not referenced by your database context. The model class should contain the properties you'll be returning from your stored proc. Then use
context.Database.ExecuteSqlCommand("storedProc", params)
// OR
context.Database.SqlQuery<YourEntityType>("storedProc",params);

Related

How to use Entity framework to pass Table Valued parameter to Stored procedure

I have tables with 2 level hierarchy, Parent->Child->GrandChild
I have create stored procedure with three table valued input parameter ParentTable, ChildTable, GrandChild Table.
Now, I want to consume it in .net using entity framework.
Solution all over internet is, create DataTable in .net , store data in it and pass the same as parameter in stored procedure.
But, I want to use entities instead of data table as data is stored in entity objects. Please suggest. Many Thanks.
You need to have look at this question
Create data table from entities and then pass it to the stored procedure. I haven't tried the code, just showing you the path to go. I hope it may help, looking for better solution.

What type of object is returned by EF stored procedure call?

I am using Entity Framework (v6.1) with the Database First method. I have created my EDMX file and it references a stored procedure I selected while creating the EDMX via the EF wizard. My question is how do I use what the stored procedure returns?
Below is my dbContext and the name of the stored procedure GetHtmlContent. The stored procedure takes contentId as an integer parameter.
Here is the SQL of the stored procedure GetHtmlContent ..
SELECT
HtmlContent.contentId,
HtmlContent.[Name] AS 'Name',
HtmlContent.HTML AS 'HTML',
HtmlContentCategory.CategoryTitle
FROM HtmlContent
LEFT JOIN HtmlContentCategory ON HtmlContent.CategoryID = HtmlContentCategory.HtmlContentCategoryID
WHERE HtmlContent.ContentId= #ContentId
Below is what I get when I hover over the stored procedure method contained within the dataContext to see what is returned.
System.Data.Entity.Core.Objects.ObjectResults<GetHtmlContent_Result> dbContext.GetHtmlContent(contentId)
This is where I am getting confused ...
Is the <GetHtmlContent_Result> a type representing the dataset returned by the stored procedure?
What is System.Data.Entity.Core.Objects.ObjectResults?
Since I am accepting a collection of records from the stored procedure do I need to create a class to hold the results of the stored procedure?
Is the a type representing the dataset returned by the stored procedure?
GetHtmlContent_Result is representing each record that is produced by stored procedure.
HtmlContent.contentId,
HtmlContent.[Name] AS 'Name',
HtmlContent.HTML AS 'HTML',
HtmlContentCategory.CategoryTitle
What is System.Data.Entity.Core.Objects.ObjectResults?
The ObjectResult is an enumerable collection class, but it is a
forward-only collection so once it has been enumerated, you cannot
enumerate it again. For example, if you call ToList on the result,
e.g., GetDetailsForOrder(3).ToList(), then you cannot subsequently
provoke another enumeration by calling ToList again, binding the
results to a control or executing a foreach over the results. - MSDN
Since I am accepting a collection of records from the stored procedure do I need to create a class to hold the results of the stored procedure?
It's just like other entities that represent tables in the database, a POCO. You can use it directly.

stored procedure mapping Entity Framework

We're using a Function Import in an EF4 model to populate an existing entity in our Model. The entity in the model has a Key field of Id which we're struggling to map as our stored procedure doesn't return an Id field. I've tried setting the value in the mapping to a literal value of 0 but that fails with an EntityCommandExecutionException and the following exception text.
The data reader is incompatible with the specified 'Candidate'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.
Short of modifying the stored procedure to return a dummy Id field can anyone recommend what the best approach is for this as the dummy field option feels very clunky to me.
Many Thanks
If you can't return enough data to fully materialize the entity -- and the Id field is certainly going to be required for that -- then you need to change the return type on the proc to be a complex type instead of an entity.
Use another POCO class with the same structure to receive the results of the stored procedure call, here's an example:
string sp = string.Format("EXEC dbo.spComercialesAsociadosActivos {0}", idComercialPrincipal);
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<InfoComercial>(sp);
In this case "InfoComercial" is a POCO class with the same structure as "Comercial", which is tied up to EF code first in the DBContext, then I used this independent class in the viewModel to create a disconnected "Comercial", it's not an ideal solution but will work fine until EF 5 comes with SP support.

ADO.NET Ef4- How can i map a entity to stored procedure without mapping to table

We are using ado.net entity framework 4.0 for our database layer and I am a newbie to ado.net entity framework. I have created entity via adding a entity in entity framework. I want to map that entity with stored procedure only not table of the database. Stored procedure will return same column as entity. How it is possible and how i can do that without mapping to table?
Here is a complete walkthrough http://msdn.microsoft.com/en-us/library/cc716679.aspx
Its not possible because an ObjectSet is an IQueryable and mapping an ObjectSet to stored procedure would not give u an IQueryable because stored procedures by their very nature cannot be composed. The best you can do is take the content inside the stored procedure and put into a view and map the view to an ObjectSet which is possible.
You need to create a complex type, not an entity. Open up the model browser and import your stored procedure as a "function import" (your SP must not use #tempTables but you can use #tableVariables instead); in the function import wizard you'll see a "create complex type" button.
The SP becomes a method in the model context and you can use it to get IEnumerable[TheComplexType].
In EF4.1 code-first it's even simpler, you put a [ComplexType] attribute on top of any class and you can use that type as a return type for context.ExecuteStoreQuery[T]. If your properties are named exactly as the returned columns are (and the types line up), the mapping is "magic" - it just works.

Entity framework function import, can't load relations for functions that return entity types

I've created a function import that returns the results of a stored proceedure as one of my entities. however I can't seem to traverse my through navigation properties to access the data in other entities. I know that you can use include() for objectQueries but can't find anything that will force the EF to load my relations for entity results of function imports.
Any ideas??
Thanks in advance.
This is not possible in EF 1.0
The reason is that EF will consider stored procedure values to be just values and not navigation properites.
For example, Employee entity has multiple Order entities. In Order you have a property called EmployeeID. When the database fills your query using include statements, it creates 1 projection query in SQL to populate all of the Order data that a particular Employee could have.
So if I said
var employee = context.Employees.Include("Orders").Where(e => e.ID == 1).First();
var orders = employee.Orders;
The SQL for the first query will create a projection query which will contain orders where the EmployeeID = 1.
Now when your stored procedure runs, this can do any code behind the scenes (in otherwords it can return any set of data). So when SQL runs the stored procedure, it just runs the code in that stored procedure and does not have any knowledge that EmployeeID on Order is an FK to that property. Additionally, if your stored procedure returns an Employee entity, then you are looking at another scenario where you will not even have an OrderID to pursue.
To work around this though, you can setup your query in EF using Include statements that can mirror any stored procedure. If you use the proper mix of .Select and .Include statements you should be able to do the same thing.