How to present a calculated options column with EF Code First?

I have a situation where I have a table of records for which I will query, but in some cases I will have additional information.

For example, if I have a table people, I want to be able to search by name, but I also want to store some coordinates and search by their location, but also expose this distance in the object model, So, for example, suppose the table peoplelooks something like this:

PersonId int
Name nvarchar(100)
Address nvarchar(100)
Latitude float(10,6)
Longitude float(10,6)

And the entity class is defined as follows:

public class Person
{
     public int PersonId { get; set; }
     public sting Name { get; set; }
     public float Latitude { get; set; }
     public float Longitude { get; set; }
}

Then I can easily find the person by name using:

var people = from p in myDb.People where p.Name.Contains("joe");

Now I have a custom function called CalculateDistancethat I created to handle these distance calculations. And so my SQL will look something like this:

String sql = "SELECT *, dbo.CalculateDistance(" + location.X + ", " + location.Y + ", Latitude, Longitude) AS Distance FROM people ORDER BY Distance

? :

public virtual float Distance { get; set; }

, "". Person:

public class PersonWithDistance: Person {
    public float Distance { get; set; }
}

.

- ? ?

+3
2

, PersonResult, Id, Distance Person, :

public class PersonResult {
     [Key]
     public int PersonId { get; set; }
     public double Distance { get; set; }
     public virtual Person Person { get; set; }
}

:

var results = myDb.PersonResults.SqlQuery("EXEC PeopleByDistance " + lat + ", " + lng);

, Person:

foreach (PersonResultresult in results)
{
    result.Person = myDb.People.Where(p => p.PersonId == result.PersonId).FirstOrDefault();
}

, . , .

+1

. - , . .

, - , , . :

[NotMapped]
public float Distance { get; set; }

API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Person>().Ignore(p => p.Distance);
}
+4

All Articles