Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I represent an option calculated column with EF Code First?
    primarykey
    data
    text
    <p>I have a situation where I have a table of entries that I'll be querying on, but in some cases I'll have additional information available.</p> <p>For instance, if I have a table of <code>people</code>, I want to be able to search by name, but I also want to store some coordinates and search based on their location, but also expose that distance in the object model. So, for instance, suppose my <code>people</code> table looks something like this:</p> <pre><code>PersonId int Name nvarchar(100) Address nvarchar(100) Latitude float(10,6) Longitude float(10,6) </code></pre> <p>And the entity class is defined like this:</p> <pre><code>public class Person { public int PersonId { get; set; } public sting Name { get; set; } public float Latitude { get; set; } public float Longitude { get; set; } } </code></pre> <p>Then I can easily find a person by name using: </p> <pre><code>var people = from p in myDb.People where p.Name.Contains("joe"); </code></pre> <p>Now, I have user-defined function called <code>CalculateDistance</code> that I've created to handle this distance calculations. And so my SQL will look something like this:</p> <pre><code>String sql = "SELECT *, dbo.CalculateDistance(" + location.X + ", " + location.Y + ", Latitude, Longitude) AS Distance FROM people ORDER BY Distance </code></pre> <p>How do I represent this in code? I've tried adding a property like this to the class:</p> <pre><code>public virtual float Distance { get; set; } </code></pre> <p>But then the name queries fail because there is no Distance column. I also tried extending the Person class:</p> <pre><code>public class PersonWithDistance: Person { public float Distance { get; set; } } </code></pre> <p>But that caused even more problems with the way the mappings are generated. </p> <p>What's the correct way to implement something like this? Do I have to create an entirely separate separate class for the results from the distance query?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload