无法将类型"System.Int64"强制转换为"System.Object"类型.LINQ to Entities仅支持转换实体数据模型基元类型

Aam*_*mir 9 c# visual-studio-2010 entity-framework-4 c#-4.0

我创建了一个EF 4C#来获取一些数据.我正在使用Linq.其内容如下:

    public List<object> GenerateCallTrackingReport(int startRowIndex, int maximumRows, int createdByID)
    {
        var query = from c in this.ObjectContext.CallLogs                        
                    select new
                    {
                        CallLogID = c.CallLogID,
                        DomainName = c.CallDomain.FullName,
                        CreatedByID = c.CreatedByID,
                        CreatedBy = c.CreatedByUser.FirstName + " " + c.CreatedByUser.LastAccessIPN,
                        CalledOn = c.CallDate,
                        IssueResolutionTime = c.IssueResolutionTime,                            
                        CallType = c.CallType.FullName,
                        CallDescription = c.CallDescription,
                        CustomerName = (c.CustomerID > 0 ? c.Customer.FirstName + " " + c.Customer.LastAccessIPN : c.TempCaller.FirstName + " " + c.TempCaller.LastName),
                        CustomerEmail = (c.CustomerID > 0 ? c.Customer.Email : string.Empty),
                        CustomerResponse = c.Response.FullName,
                        IsPending = c.IsPending,
                        NeedFurtherContact = c.NeedFurtherContact
                    };

        if (createdByID > 0)
            query = query.Where(c => c.CreatedByID == createdByID);

        if (maximumRows > 0)
            query = query.Skip(startRowIndex).Take(maximumRows);

        return query.ToList<object>();

    }
Run Code Online (Sandbox Code Playgroud)

这导致以下错误:

Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.
Run Code Online (Sandbox Code Playgroud)

任何想法我是否得到这个错误?

谢谢

Ser*_*rvy 5

一旦你的ToList电话,你想在C#中要执行它,而不是在数据库中。使用AsEnumerable的话,的一种方式“停止做这种东西在数据库中,做它在C#。”

ToList在最后添加它,以便在数据库上完成其他所有操作。


Aam*_*mir 5

解决

我有两个问题,每个都会导致此错误:

1.我正在访问NULLABLE实体属性,而不检查它们是否有值.假设CustomerIDNULLABLE,所以我的查询变成了这样的东西!

    var query = from c in this.ObjectContext.CallLogs                        
                select new
                {
                    CallDescription = c.CallDescription,
                    CustomerID = c.CustomerID.HasValue ? c.CustomerID.Value : 0,
                    CustomerName = c.CustomerID.HasValue ? c.Customer.Name : ""
                };

    if (maximumRows > 0)
        query = query.Skip(startRowIndex).Take(maximumRows);

    return query.ToList<object>();
Run Code Online (Sandbox Code Playgroud)

因此,在访问它之前,只需通过其HasValue属性检查任何空值(选择部分中的第二行).

2.我还试图在select语句中将整数转换为字符串.所以我只是决定用HTML转换而不是直接在这里进行转换.这解决了我的问题.

希望这有助于某人!