枚举类型错误 - 无法创建常量C#

时间:2017-01-18 18:12:28

标签: c# asp.net-mvc linq razor

我想要做的是,我的PackageModel没有项目Account。所以我创建了一个ViewModelPackageViewModel)所以我可以添加一个Account项。

我收到以下错误。有人可以帮我分类吗?

  

其他信息:无法创建类型的常量值   'MyPROJ.Models.Account'。只有原始类型或枚举类型   在这种情况下得到支持。

模型如下:

public class PackageModel
{
    public int ID { get; set; }
}

VIEWMODEL如下:

public class PackageViewModel
{
    public int ID { get; set; }
    public Account acc {get; set;}
}

我的控制器正在执行以下操作:

Account a = new db.Account.Find(currentLoggedInUser);
var xxx = db.PackageModel.Where(y => y.ID== 1)
            .Select(x => new PackageViewModel()
            {
                ID= x.ID,
                acc = a
            });

return (xxx.ToList());

查看

<div class="myall">
    @Html.Partial("_SomePage", @Model.First().Account)    
    ...
</div>

1 个答案:

答案 0 :(得分:2)

您不能在Linq-to-Entities查询中使用闭包捕获变量,这些变量是非平凡类型。

Account a = db.Account.Find( currentLoggedInUser );
var xxx = db.PackageModel.Where(y => y.ID== 1)
        .Select(x => new PackageViewModel()
        {
            ID= x.ID,
            acc = a // <-- you're capturing `a` which is an `Account`, a class type, not a trivial value or object
        });

更改它,以便在Linq-to-Entities查询完成后,使用SelectToList AsEnumerable >

Account a = db.Account.Find( currentLoggedInUser );
var xxx = db.PackageModel
        .Where( p => p.ID == 1 ) // <-- this part is Linq-to-Entities
        .AsEnumerable() // <-- this causes the rest of the Linq construct to be evaluated in Linq-to-Objects
        .Select( p => new PackageViewModel() // <-- this part is Linq-to-Objects
        {
            ID = x.ID,
            acc = a // <-- now you can capture non-trivial values
        });

...但是我注意到您正在使用Where,但是如果谓词返回单个元素(假设ID是唯一的),则应使用SingleOrDefault代替:

Account acc = db.Account.Find( currentLoggedInUser );
Package package = db.PackageModel.SingleOrDefault( p => p.ID == 1 );
if( package == null ) throw new InvalidOperationException("Package not found");

PackageViewModel vm = new PackageViewModel() { ID = package.ID, Acc = acc };
return this.View( vm );