【问题标题】:Extract property of object from entity framework query从实体框架查询中提取对象的属性
【发布时间】:2015-07-27 13:45:18
【问题描述】:

我是 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 提取到列表中的最简单方法是什么。

【问题讨论】:

  • 使用EF的时候为什么要写sql查询?你失去了 EF 带给你的所有强类型的魅力
  • @Kritner 好吧,实体表名应该是动态的,我认为格式化 sql 字符串是最简单的。你怎么看?创建查询不会让我做类似... select fname from peopleEntity.Person ...

标签: c# entity-framework entity iqueryable


【解决方案1】:

我将您的问题解释为“获取提供的 personId 的名字”。假设您的 peopleEntities 包含 DbSet&lt;Person&gt; 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
}

【讨论】:

  • 那么如果实体Person和字段Fname是动态的呢?这意味着我不知道我在处理哪个实体,也不知道我想要的字段。
  • 这听起来与您在问题中所问的情况截然不同。 stackoverflow.com/questions/21084916/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多