How to print an unmatched value

I use complex SQL queries, I have to use SqlQuery ... in a simple way:

Model:

public class C { public int ID { get; set; } [NotMapped] public float Value { get; set; } } 

CONTROLLER:

 IEnumerable<C> results = db.C.SqlQuery(@"SELECT ID, ATAN(-45.01) as Value from C); return View(results.ToList()); 

VIEW:

 @model IEnumerable<C> @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.Value) } 

and the result for item.Value is NULL.

So my question is: how can I print the calculated value from SQL Query?

Thank you for your help.

+4
source share
1 answer

I would conclude that Value is 0, that EF does not map the returned columns to properties that are not displayed in the model.

What you could try as an alternative is to define an auxiliary type ...

 public class CHelper { public int ID { get; set; } public float Value { get; set; } } 

Then query into this type and copy the values ​​into your object afterwards:

 IEnumerable<C> results = db.Database.SqlQuery<CHelper>( @"SELECT ID, ATAN(-45.01) as Value from C") .Select(ch => new C { ID = ch.ID, Value = ch.Value }); 

(Normally in a LINQ-to-Entities query, you cannot design an object with Select . But I believe that Select in the above example does not affect the database query and is LINQ-to-Objects in memory, so this should be allowed. I not sure though.)

Note that the results collection is not bound or contextually tracked, but I don’t think you need it to request a GET to render the view.

Of course, you can create your view directly from the CHelper class as a view model and omit the conversion to a C object.

+1
source

Source: https://habr.com/ru/post/1442772/


All Articles