当前位置: 动力学知识库 > 问答 > 编程问答 >

entity framework 4.1 - Is it possible to map a database calculated value to an 'Ignored' property with code first

问题描述:

Seeing as EF doesn't fully support SQL spatial data types i was hoping to work around it for the time being.

Although working with code first I have a stored procedure that uses the sql2008 r2 spatial datatype range formulas. My objective was to return the distance from each object to the queried location.

With some help from the answers below I've modified my code to the follwing

I have a simple class 'Vacancy'

public class Vacancy

{

public int Id { get; set; }

public string Title { get; set; }

}

public class VacancyWithRange : Vacancy

{

public int Calculated { get; set; }

}

I'm then querying the context directly in a method like this

 public List<Vacancy> Get()

{

Context db = new Context();

var context = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)(db)).ObjectContext;

db.Database.Connection.Open();

DbCommand cmd = db.Database.Connection.CreateCommand();

cmd.CommandText = "select *, [Calculated distance from query to vacancy object] as Calculated from Vacancies";

cmd.CommandType = System.Data.CommandType.Text;

var result = context.Translate<VacancyWithRange>(cmd.ExecuteReader()).ToList();

foreach (VacancyWithRange v in result)

{

db.Vacancies.Attach(v);

}

return result;

}

The foreach loop at the end of the Get() method successfully attaches the VacancyWithRange to Vacancies so I have access to related objects via lazy loading.

As far as I can tell this seems to be a viable solution for the time being to get 'custom' calculated data back from the database with code first.

Thanks for reading.

网友答案:

I didn't try it but I expect it will not work. The reason is that Vacancy is mapped entity and once you try to Translate query result into mapped entity, EF will use defined mapping for the translation. Here comes the problem: in the mapping you specified that the Calculated property as not mapped so the mapping will not populate this property.

What you can try is defining a new type which is not mapped and includes your Calculated property (you can also try to derive custom type from Vacancy and just add the calculated property). Then you can try to use:

using (Context db = new Context()) 
{
    string queryText = "select *, [Some random calculated value] as Calculated from Vacancies";
    var data = db.Database.SqlQuery<VacancyWithCalculation>(queryText);
}

Names and types of properties in your new type must match names and types of columns in result sets because there is no explicit mapping. EF only use convention by matching result set columns and class properties by name.

Btw. context is disposable so don't forget to release it.

网友答案:

You should specify in your mapping DatabaseGeneratedOption.Computed i.e. using HasDatabaseGeneratedOption method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: