0

Is there a simple way to handle properties that are only mapped some of the time? For example:

I have a products table and products entity. Most of the time I use LINQ to SQL to execute the equivalent of:

select * from products where...

However, occasionally, I manually write a SQL query that is more like:

select products.*, someOtherVal, anotherVal from products join....

As far as I know, I can't add someOtherVal and anotherVal to my entity because they are not always mapped to a column.

Note: I realize it might be better to properly set up all of my entities and relationships and not use Entity.SqlQuery(). I'm just wondering if there's a quick way to accomplish my goal for now. I will make improvements later as I continue converting my application to EF.

jeynny
  • 29
  • 4
  • Are you looking for something like [this](https://stackoverflow.com/questions/37324/what-is-the-syntax-for-an-inner-join-in-linq-to-sql) – FortyTwo May 23 '17 at 20:59
  • No, the join isn't the problem. I need a way to handle mapping of columns that are only included in the result set some of the time. – jeynny May 23 '17 at 21:27
  • No, it's not possible, so better start doing it the way you mentioned right now. Of course you could create and use a separate non entity class (aka DTO) and project into it using `DbContext.Database.SqlQuery` method. – Ivan Stoev May 23 '17 at 23:54
  • @IvanStoev OK, thanks for the info! – jeynny May 24 '17 at 11:56

1 Answers1

1

Use anonymous types.

The IQueryable variable you create is not executed until you enumerate over it. If the Expression in your IQueryable uses only some properties of your product, only those properties are requested in your query:

var myQuery = mydbContext.Products           // join products and OtherTable
   .Join(myDbContext.OtherTable,
       product => product.SomeForeignKey,    // from product use SomeForeignKey
       otherThing => otherThing,PrimaryKey,  // from otherTable use PrimaryKey
       (product, otherThing) => new          // when these key Match
       {                                     // create an anonymous object
           X = product.X,                    // with the Properties you want
           Y = product.Y,           
           Z = otherThing.Z,
       };

Note: the query is still not performed. Now If you perform the query, for instance because of a ToList(), only the requested parameters are Selected in your SQL

var result = myQuery.ToList();
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116