How do I represent an option calculated column with EF Code First?

纵饮孤独 提交于 2019-12-05 18:22:45

This is not very nice design. You should have distance as a method of either Person or some helper class and compute distance in your application not in database. It whould also require transfering location to the person.

Anyway if you want to add some property which is not mapped to column in database you must exclude it from mapping. This can be done either by attribute:

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

or by fluent API:

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

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

Well I ended up creating a PersonResult class which contains an Id, Distance and a Person object, like this:

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

I populate that from a stored procedure like this:

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

And loop through the results to populate the Person objects:

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

That seems to work well. Although I'm not sure that's the best way to handle it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!