Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Complex Types to results form SqlQuery in Entity Framework

I am calling a stored proc using SqlQuery, the result is supposed to be a graph of objects, i.e.

public class Person
 {
   public int Id{get;set;}
   public string FullName {get;set;}
   public Address HomeAddress {get;set;}
   public Vehicle PrivateVehicle {get;set;}
 }

But SqlQuery wont map the Address and Vehicle. It only maps the column names to the properties.

Is there a work around this? How else can I do the mapping?

I found this:

.. what you can't do is return graphs of objects, e.g. entities that contain properties of complex types.

like image 273
robasta Avatar asked Jan 06 '14 12:01

robasta


People also ask

How do I add complex type to Entity Framework?

On the designer surface, select one or more properties (excluding navigation properties) of an entity, then right-click and select Refactor -> Move to New Complex Type. A new complex type with the selected properties is added to the Model Browser. The complex type is given a default name.

What are complex types in C#?

A complex type is a set of properties that exist in its own object for C#, but are mapped to columns on an already existing table (the one for the entity that contains it), instead of having its own table (which would need a key, etc.).

Which method is used to retrieve data using SQL query statements in EF?

SqlQuery() Use the DbSet. SqlQuery() method to write raw SQL queries which return entity instances. The resulted entities will be tracked by the context, as if they were returned by the LINQ query.


1 Answers

Entity Framework (up through 6 anyway) doesn't support mapping raw SqlQueries to an object graph, only as a simple entity.

You can use standard LINQ with standard Entity Framework reference mapping between them, and use Includes or whatever else you need.

But if standard LINQ to EF won't work because your SqlQuery uses SQL functions or stored procedures or something, then you're out of luck.

PS: Posting your SQL query might help in the future so the answer can be more specific to your problem.

like image 105
Jon Adams Avatar answered Sep 24 '22 03:09

Jon Adams