无法将Lambda表达式转换为类型“string”,因为它不是委托类型。

16
在我的控制器中,我正在尝试使用EF4中的include选取相关实体,但是Lambda表达式抛出了以下错误。
我在Entity类中定义了相关实体。
public class CustomerSite
{
    public int CustomerSiteId { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

然后在我的控制器中有:

 var sites = context.CustomerSites.Include(c => c.Customer);

 public ViewResult List()
 {
    var sites = context.CustomerSites.Include(c => c.Customer);
    return View(sites.ToList());
 }

请问有没有人能够友善地指出我在这里做错了什么?

5个回答

97

好的,这篇文章相当旧了,但我在这里回复以更新它。好的,Include() 方法使用 Entity Framework 4.1 具有扩展方法,并且还接受 lambda 表达式。

context.CustomerSites.Include(c => c.Customer);

这是完全有效的,你所需要做的就是使用这个:

using System.Data.Entity;

13
在 System.Data.Entity 命名空间中,Include 是一个扩展方法,您需要添加:

Include 是 System.Data.Entity 命名空间中的扩展方法,您需要添加:

using System.Data.Entity;

那么你可以使用Lambda表达式,而不是字符串。


9

Include 方法需要一个字符串参数,而不是一个 lambda 表达式:

public ViewResult List()
{
    var sites = context.CustomerSites.Include("Customer");
    return View(sites.ToList());
}

当然,你可以编写一个自定义扩展方法,它可以使用lambda表达式,并使你的代码独立于某些魔术字符串和重构友好。但是,请不要将EF自动生成的对象传递给视图,请使用视图模型

1
谢谢,但说起来容易做起来难,我找不到一个实际的例子来展示如何使用视图模型返回相关数据。 - Liam
@Darin Dimitrov,你能否请过来看一下我发布的一个类似的问题。http://stackoverflow.com/q/16060884/1356321 - Pomster
请问您能提供下面更新的参考链接吗:https://dev59.com/r2w15IYBdhLWcg3wT5_2#9428710 - Bolt Thunder
1
一定要查看Entity Framework的后续版本的替代答案,因为允许使用lambda表达式。 - Fenton
上面的答案已经过时了。正确的答案如下:使用 System.Data.Entity; - Pxtl

2

Include接受一个字符串参数,而不是lambda表达式。
请将其更改为CustomerSites.Include("Customer")


1
如果您在Razor中遇到此错误:

Ex:

@Html.RadioButtonFor(model => model.Security, "Fixed", new { @id = "securityFixed"})

C#不知道如何将字符串转换为有效的布尔值或已知类型。因此,请按照以下方式更改您的字符串:
@Html.RadioButtonFor(model => model.Security, "True", new { @id = "securityFixed"}) 

or

@Html.RadioButtonFor(model => model.Security, "False", new { @id = "securityFixed"})    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接