I currently use a database-first approach using Entity Framework (EF). I'm investigating different ways of calling stored procedures (stored procedures that are NOT tied to entities) using EF. Currently, I'm using the approach found here using the designer (in this approach, I import a stored procedure, create a function import and use a complex type as my mapped object). I don't like this because it relies on a bloated EDMX file and it causes merge conflicts in source control when two or more people perform this procedure and check in their code.
I found this post which claims I can call a stored procedure and map to a plain old C# object (POCO).
My question is if I want to map to a POCO to a stored procedure in EF not using the designer approach, how do I get aliases for column names? For example, let's say I call a stored procedure and get a particular column back named "CustomerID" and I want the property mapped to it to be named "Id" instead of "CustomerID". How can I do this without using the designer approach?
Something like the following should work:
[your db context].Database.SqlQuery<[your POCO class]>("[name of stored proc] [comma separated parameters]", parameter1, parameter2, .....)
Here's example from one of my applications:
_context.Database.SqlQuery<Library>("usp_paged_select_libraries #userId, #offset, #fetch", userIdParameter, offsetParameter, fetchParameter);
Within your POCO you would mark up your properties with:
[Column("[your alias here]")]
Related
I am using EF reverse POCO generator. When I save the .tt file it automatically generates the return model of all the stored procedures.
In couple of my SP's, I have a user defined table type as one of the input params. For those SP's, my POCO is not creating the return models.
Earlier I had this issue for normal SP for which I used a return query from the temp tables. Adding SET FMTONLY OFF on top of the SP fixed that.
I am pretty sure it is with using the user defined table types that is causing the issue because when I just remove them, the return models are generated.
I am looking for a fix to this. Any help would be greatly appreciated.
I am using EF 6 to connect to an existing SQL database. I want to generate a model for some existing entities and non-CRUD stored procedures. From visual studio, I am adding a new "ADO.NET Entity Data Model" and selecting "Code First from Database" for the model content. However, the only database objects that are available to me are Tables and Views. Stored procedures aren't available. Is this by design or am i missing something here?
You need to define a DTO for each stored procedure. You just create simple classes where the propery names of the classes match the name of the columns that are returned by the stored procedure. So, when you call the Stored Procedure from EF, your objects are built and populated. The performance is great!
Here I'm pasting an example:
dbContext.Database.CommandTimeout = 3600;
List<CarsDTO> objs = dbContext.Database.SqlQuery<CarsDTO>(
"spGetCars #carMakeId", new SqlParameter("carMakeId", id)
).ToList();
I am wondering if there is a way, using Entity Framework, of mapping results from arbitrary sql, like ResultSetMapping in Doctrine. I know i can create a configuration class doing the mapping but that requires me registering the class as an entity type.
What i am trying to do is utilize the materialization element (Object Services) of EF without the rest of EF. Sometimes i have results from a proc with cryptic or less meaningful column names, but need to map to classes with more meaningful property names but have no permission to alter the proc definition, e.g:
exec dbo.getRecDetail #var
returning columns :
sd, ed, nm, ....
which should be mapped to a class such as:
class Obj{
public DateTime StartDate; //sd
public DateTime EndDate; //ed
public String Name; //nm
....
}
If you are using .EDMX file (designer) with database first approach you can import your stored procedures into the model (simply select stored procedures in wizard) and map their results to complex types.
It actually works with arbitrary SQL queries as well but those queries cannot be imported into the model automatically (because they don't exist in your database). It requires manual modification of storage model in EDMX file (it is XML - check documentation for Function and CommandText elements). Once you do that you cannot use update from database feature of the designer any more because it would delete your custom queries.
If you are using code first there is currently no option to map results of stored procedures or custom queries. You can only use automatic mapping which requires your class to have properties with exactly same name as columns in result sets.
been using ExecuteQuery with some success, i.e. where AccessRights is my dto and queryString contains "Exec sp_name param1,param2 etc"
var accessRights =
this.db.ExecuteQuery<AccessRights>(queryString, sqlParams.Values.ToArray()).AsQueryable();
Everything works perfect if what returns from the stored procedure can be mapped perfectly to the type (dto) that i pass in the generic ExecuteQuery
Problem is now i have a stored procedure that returns a non standard column name.
Basically my i hav my AccessRights class (dto) which contains, "userId", "accessRightId", "Description"
but the new stored procedure returns UserId, AccessRightId, "TemporaryDescription".
now i can't change it as other things depend on it... if I do
var accessRights =
this.db.ExecuteQuery<AccessRights>(queryString, sqlParams.Values.ToArray()).AsQueryable();
then i don't see "TemporaryDescription", which i suppose is logical as it doesn't exist
What i need to do is map temporaryDescription back to description.
Any body has any idea how to do this?
You could try adding the [Column(...)] attribute; no idea if that'll work.
A few options that leap to mind:
build a class that does map 1:1 (by name), and then translate this data (via Select, or a LINQ query) into your actual intended class
write a wrapper SP that renames the column (not nice; you'd need a temp table, presumably forcing recompile due to DDL/DML interleave)
drag the SP onto the data-context designer and rename the columns manually in the generated types (consdier this as an automated implementation of the first bullet)
move (refactor) the interesting part of the SP into a UDF that you can call from your existing sp, and use the UDF directly from the data-context (drag the UDF onto the designer)
I already have an entity model in a separate dll that contains various objects that I need to use. I don't really want to create or duplicate entities using the EF designer. Instead I would like to configure it so that when I call a stored procedure it will map certain columns to specific properties.
I know you can do something VERY close to this using a custom DataContext in LinqToSql. The problem is you can't assign columns to complex property types. For example: I might have a columns returned that contain the address for a user. I would like to store the address details for the user in an Address object that is a property of a User object. So, Column STREET should map to User.Address.Street.
Any ideas?
There are a couple of options here.
You can create a "Complex Type" and map that to the procedure result. However, you have to do that in your EDMX; it's not supported by the designer. Read this article for details. Note that Complex Types are not entity types per se, so this may or may not fit your needs. But you can find examples for stored procs which use "Address".
You can change the visibility of your procedure to private, and then write a public interface for it in any manually-written partial class file which does the mapping that you want. Or just overload the procedure.