错误:“在此上下文中仅支持基元类型或枚举类型”

时间:2013-06-27 21:19:39

标签: c# asp.net linq-to-entities dbcontext

查看相关帖子但仍有困难。这是我的代码:

var id = Request.QueryString["id"].AsInt();
var accountNum = Request.QueryString["accountnum"];

var orderIDs = new List<OrderID>();

// Order IDs are in the form: OrderNum-OrderLine[,...]
// e.g. orderids=41417-6,36703-1

foreach (var orderID in Request.QueryString["orderids"].Split(',')) {
    var components = orderID.Split('-');
    orderIDs.Add(new OrderID() {
        OrderNum = components[0].AsInt(), 
        OrderLine = components[1].AsInt()
    });
}

var dbContext = new TelecomEntities();
var assignedLines = dbContext.LineAssignments
    .Where(a => orderIDs
        .Any(i => a.OrderNum == i.OrderNum && a.OrderLine == i.OrderLine))
    .ToList();

运行时,我收到错误:无法创建“OrderID”类型的常量值。在此上下文中仅支持原始类型或枚举类型。

根据我在其他帖子中看到的内容,我无法执行查询,因为orderIDs不在dbContent上下文中。

编辑:OrderID类

public class OrderID
{
    public int OrderNum { get; set; }
    public int OrderLine { get; set; }

    public OrderID() { }
}

2 个答案:

答案 0 :(得分:0)

我认为它是AsInt(我以前从未见过,但我认为它是WebPages的一部分)。

你是否在foreach中得到错误?如果是这样,请尝试这样做:

        foreach (var orderID in testOrderIDs.Split(','))
        {
            var components = orderID.Split('-');
            orderIDs.Add(new OrderID()
            {
                OrderNum = int.Parse(components[0]),
                OrderLine = int.Parse(components[1])
            });
        }

答案 1 :(得分:0)

问题是EF无法将您的比较转换为OrderID对象到SQL。一种选择可能是将订单ID保留为字符串:

var id = Request.QueryString["id"].AsInt();
var accountNum = Request.QueryString["accountnum"];

string[] orderIDs;

// Order IDs are in the form: OrderNum-OrderLine[,...]
// e.g. orderids=41417-6,36703-1

orderIDs = Request.QueryString["orderids"].Split(',');

var dbContext = new TelecomEntities();
var assignedLines = dbContext.LineAssignments
    .Where(a => orderIDs
        .Any(on => on.Equals(a.OrderNum + "-" + a.OrderLine))
    .ToList();