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

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.

Related

EF and stored procedures to populate entries for an Entity

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);

DTO/POCO with Entity Framework

I'm using EF5 Model First. I don't really understand what are the auto-generated classes from the EDM. According to some documentation this classes are POCOs but why are they used in the context ?
Assuming I have a Student entity, then I get a Student POCO class and a DbSet StudentSet property in my context.
Will this next instructions put a POCO in my database ?
MyContext.StudentSet.Add(johndoe);
MyContext.SaveChanges();
So EF uses POCO to transfer data ? Actually I miss the step when POCO exchange data with entities or DTO and when the entities put data in the database.
The generated classes from the EDM is the ORM / Persistence classes. You use that classes to query / make changes from / to database. You need to translate any DTO object to POCO object when about making changes to database.
ORM is about mapping object to data in database, instead of dealing with insert into syntax to insert record to database in the application, you use StudentSet.Add to add a new data. The johndoe information will be translated into sql syntax, EF will map each property to each column when translating it into query.
The Add method will store the johndoe information as Added in the memory but it will not be executed right away to the database. If you have another Add method, it will be marked as Added too. The moment you call SaveChanges, all the changes will be saved into database by sending a generated query.
The mapping between DTO and EF entity happens before you add the johndoe. You might have another DTO class that is used in the UI. You need to map it manually or using mapper library to create a POCO object from a DTO object. For example:
// studentDto as parameter
var johndoe = new Student
{
Name = studentDto.StudentName,
Age = studentDto.StudentAge
};
MyContext.StudentSet.Add(johndoe);
// studentDto might have another information as well
var johndoeSubject = new Subject
{
Name = studentDto.SubjectName,
Years = studentDto.SubjectYears
};
MyContext.SubjectSet.Add(johndoeSubject);
MyContext.SaveChanges();

Creating a dynamic complex type in entity framework

I have created a stored procedure which returns columns dynamically , but i'm unable to import it into entity framework
Does anybody know how to import a stored procedure that returns columns dynamically
EF doesn't support stored procedure with dynamic result set. The result set must be fixed for EF to map it to complex type / entity type.

Entity framework: Database first/Code first hybrid

I am trying to create a custom Entity Framework (4.2) entity that would be mapped to my database like it would be done in a Code first approach.
The issue is that my entity framework data model is using Database first.
How can I add my custom entity to entity framework's context?
If by the Database first you mean that you already have EDMX created from exiting database you simply cannot use code first. You must create table and update model (EDMX) from the database to include it in EDMX.
Edit based on comment:
I want to create a BriefUser entity that would basically be a lighter
version of User but it would have properties retrieved from User's
foreign keys.
Well this is possible. You can either create BriefUser as common class and use projection in query.
var breifUser = (from x in context.Users
where ...
select new BriefUser
{
// Fill BreifUser's properties here
}).FirstOrDefault();
You can even refactor former code to reusable extension method:
public static IQueryable<BriefUser> ProjectUser(this IQueryable<User> query)
{
return query.Select(x => new BreifUser()
{ // Fill BreifUser's properties here });
}
and use it like:
var briefUser = context.Users.ProjectUser().FirstOrDefault(...);
It is also possible to define your new class as "entity view". The first problem is that each table can be mapped to only one entity (except some advanced concepts like inheritance or splitting) so you cannot define your BriefUser as a new entity type because mapping both User and BriefUser to UserTbl would violate this rule. You must use special construct called QueryView.
QueryView is view in mapping level. It allows you to create new mapped type which is projection of existing mapped entities defined directly in EDMX's MSL part. The projection is defined as custom Entity SQL query. The problem is that QueryView has limitations:
It doesn't offer all Entity SQL features - for example it doesn't support aggregations (which I consider as really missing feature). Without aggregations you for example cannot create a new type which will contain property counting some related entities.
It is not supported in designer. You must edit your EDMX as XML to define QueryView and you must write Entity SQL query yourselves.
Resulting type is a "view" and it is read-only.
I want to keep the EDMX file, but also be able to add an entity
(BriefUser) to EF's context.
This is not possible. Your BreifUser is only projection / view and EF is not able to track changes back to originating tables so you cannot add BreifUser to context and persist it. In case of QueryView you can achieve it if you define custom stored procedures which will no how to decompose BreifUser and modify all related tables. These stored procedures must be imported to the EDMX and mapped to data modification operations of the view entity. Btw. same will happen if you map your entity to the database view because EF takes all views as read-only.

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.