从实体框架查询中提取对象的属性

时间:2015-07-27 13:45:18

标签: c# entity-framework entity iqueryable

我是EF的新手,我在做最简单的事情时遇到了麻烦......

public class Person : DTO
{
    public String ID { get; set; }
    public String Fname { get; set; }
    public String Lname{ get; set; }
}

我想使用IQueryable<Person>ObjectReuslt<Person>从我的对象中提取Fname

 peopleEntities entities = new peopleEntities();
 string queryStr = "select value c from peopleEntity.Person as c Where c.ID=" + personID;
 IQueryable<EntityObject> query = entities.CreateQuery<EntityObject>(queryStr);

我发现CreateQuery可以返回IQueryableObjectResult。我想知道从我的查询结果中将Fnames提取到列表中的最轻微的方式。

1 个答案:

答案 0 :(得分:0)

我将您的问题解释为&#34;获取所提供的personId&#34;的第一个名字。假设您的peopleEntities包含DbSet<Person> Person,您可以执行以下操作:

public string GetFirstNameForPeron(string personId)
{
    peopleEntities entities = new peopleEntities(); // new up your EF context

    return entities
        .Person // from the person entities
        .Where(w => w.ID == personId) // Where the ID = personId
        .FirstOrDefault(); // take the first available
        .Fname; // only the Fname property
}