无法识别方法'System.String ToString()'方法,并且此方法无法转换为商店表达式

Tri*_*ing 8 c# linq-to-entities entity-framework entity-framework-4

我查看了与此相关的所有示例,但未能解决我的问题.

我正在asp .net mvc3中创建一个下拉列表.

我有一个存储库返回:

    public IEnumerable<SelectListItem> GetPropertyTypeSelectList()
    {
        var propertyTypes = from p in db.PropertyType
                                orderby p.PropertyTypeDescription
                                select new SelectListItem
                                {
                                    Text = p.PropertyTypeDescription,
                                    Value = p.PropertyTypeId.ToString()
                                };
        return propertyTypes;
    }
Run Code Online (Sandbox Code Playgroud)

我的viewmodel看起来像这样:

public class AddPropertyViewModel
{
    public Property Property { get; set; }
    public IEnumerable<SelectListItem> PropertyTypes { get; set; }
    public IEnumerable<SelectListItem> FurnishedTypes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我为HttpGet"创建"动作的控制器如下所示:

    public ActionResult AddProperty()
    {
        AddPropertyViewModel viewModel = new AddPropertyViewModel
        {
            PropertyTypes = websiterepository.GetPropertyTypeSelectList()

        };
        return View(viewModel);
    }
Run Code Online (Sandbox Code Playgroud)

并且视图是这样的:

    <div class="editor-label">
        @Html.LabelFor(model => model.Property.PropertyType)
        @Html.DropDownListFor(model => model.Property.PropertyType, Model.PropertyTypes)
    </div>
Run Code Online (Sandbox Code Playgroud)

我收到上面的错误.从我所看到的,看起来像ToString()导致问题.但我不确定如何纠正它.

谢谢.

Dar*_*rov 21

LINQ to SQL不知道如何将.ToString()调用转换为SQL表达式.

所以替换:

var propertyTypes = 
    from p in db.PropertyType
    orderby p.PropertyTypeDescription
    select new SelectListItem
    {
        Text = p.PropertyTypeDescription,
        Value = p.PropertyTypeId.ToString()
    };
Run Code Online (Sandbox Code Playgroud)

有:

var propertyTypes = db
    .PropertyType
    .OrderBy(x => x.PropertyTypeDescription)
    .ToList()
    .Select(x => new SelectListItem
    {
        Text = p.PropertyTypeDescription,
        Value = p.PropertyTypeId.ToString()
    });
Run Code Online (Sandbox Code Playgroud)

注意.ToList()在构建表达式之前急切地执行SQ​​L查询的调用直到OrderBy子句,然后.ToString()在客户端(LINQ to Objects而不是LINQ to Entities)上执行.ToString()表达式完全支持.

所以这里我们基本上构建一个SQL查询,直到OrderBy子句(包括),然后调用.ToList来急切地执行此查询并在客户端上获取结果集.然后我们继续使用.Select语句进行链接.但我们不再做任何LINQ to Entities或SQL的东西了.我们现在正在对对象执行LINQ,因为所有结果集现在都在内存中.在LINQ to Objects中执行.ToString并不会带来任何挑战.

另一种可能性是使用SqlFunctions.StringConvert知道如何将其转换为SQL 的内置函数.这样你就可以保持懒惰:

var propertyTypes = 
    from p in db.PropertyType
    orderby p.PropertyTypeDescription
    select new SelectListItem
    {
        Text = p.PropertyTypeDescription,
        Value = SqlFunctions.StringConvert((double)p.PropertyTypeId)
    };
Run Code Online (Sandbox Code Playgroud)