2

SELECT通过与 SQL Server 的普通连接,您可以指定要在简单语句中返回的列。

使用英孚:

Dim who = context.Doctors.Find(3) ' Primary key is an integer

以上返回实体拥有的所有数据......但是......我只想用 SQL 做你能做的,只得到我需要的。

这样做:

 Dim who= (From d In contect.Doctors
                     Where d.Regeneration = 3
                     Select New Doctor With {.Actor = d.Actor}).Single

给我这个错误:

无法在 LINQ to Entities 查询中构造实体或复杂类型 XXXXX。

那么...如何仅从一个实体返回选定的数据?

4

4 回答 4

1

基本上,我不确定为什么,但 Linq 无法创建复杂类型。如果您正在创建一个匿名类型,例如(对不起 c# 代码),它会起作用

var who = (from x in contect.Doctors
           where x.Regeneration == 3
           select new { Actor = x.Actor }).Single();

然后你可以去

var doctor = new Doctor() {
    Actor = who.Actor
};

但它不能像您尝试使用的那样将其构建为强类型或复杂类型

var who = (from x in contect.Doctors
           where x.Regeneration == 3
           select new Doctor { Actor = x.Actor }).Single();

另外你可能要小心使用single,如果没有具有再生编号的医生或者有多个它会抛出异常,singleordefault更安全但如果有多个匹配它会抛出异常。First或者Firstordefault更好的选择First只会在不存在并且Firstordefault几乎可以处理任何事情的情况下抛出异常

于 2012-04-22T09:37:35.210 回答
0

最好的方法是在 ViewModel 中设置想要的属性“或 DTO,如果你正在处理更高级别”然后作为你的示例,ViewModel 将是:

public class DoctorViewModel{
public string Actor {get;set;}
// You can add as many properties as you want
}

那么查询将是:

var who = (From d In contect.Doctors
                     Where d.Regeneration = 3
                     Select New DoctorViewModel {Actor = d.Actor}).Single();

抱歉,我用 C# 编写了代码,但我认为这个想法很清楚 :)

于 2012-04-22T11:49:51.360 回答
0

你可以简单地这样做:

 Dim who= (From d In contect.Doctors
                     Where d.Regeneration = 3
                     Select d.Actor).Single
于 2012-04-22T09:36:56.763 回答
0

尝试这个

Dim who = contect.Doctors.SingleOrDefault(Function(d) d.Regeneration = 3).Actor
于 2012-04-22T11:59:47.903 回答