繁体   English   中英

实体框架中的转换错误

[英]Conversion error in Entity Framework

我是实体框架的新手。 我正在尝试使用 LINQ 查询和实体框架从数据库中检索数据。

IEnumerable<Gate> lstGate = from tbsite in dc.tblSites
                            select new Gate
                            {
                              CalledInAt = DateTime.Parse(tbsite.CalledInAt.ToString(), new CultureInfo("en-GB", false)),
                              RemoteType = tbsite.RemoteType,
                              NoOfRemotes = (tbsite.NoOfRemotes == null) ? 0 : Convert.ToInt32(tbsite.NoOfRemotes),
                              GateType = tbsite.GateType,
                              NoOfRacks = (tbsite.NoOfRacks == null) ? 0 : Convert.ToInt32(tbsite.NoOfRacks),
                            };

我的Model:

public class Gate
    {

        public DateTime CalledInAt { get; set; }

        public string RemoteType { get; set; }
        public int NoOfRemotes { get; set; }
        public string GateType { get; set; }
        public int NoOfRacks { get; set; }
        public string ClickToEdit { get; set; }

    }

我收到以下错误。

“LINQ to Entities 无法识别‘System.DateTime Parse(System.String, System.IFormatProvider)’方法,并且无法将此方法转换为存储表达式。”} System.SystemException {System.NotSupportedException}

{“LINQ to Entities 无法识别方法 'Int32 ToInt32(System.Object)' 方法,并且此方法无法转换为存储表达式。”} System.SystemException {System.NotSupportedException}

正如Nilesh在评论中所指出的

您不能在LINQ中使用.Net函数,因为它将被转换为实际的SQL。 这就是它抱怨转换的原因。 示例=您不能使用Convert.toInt32,因为SQL Server不知道此函数是什么。

解决您的问题的简单方法是调用ToList() 这将执行查询并用结果填充列表。 之后,可以使用ToString()Convert.ToInt32因为这些值都在内存中,您可以自由使用.NET方法。

IEnumerable<Gate> lstGate = from tbsite in dc.tblSites.ToList()
                            select new Gate
                            {
                              CalledInAt = DateTime.Parse(tbsite.CalledInAt.ToString(), new CultureInfo("en-GB", false)),
                              RemoteType = tbsite.RemoteType,
                              NoOfRemotes = (tbsite.NoOfRemotes == null) ? 0 : Convert.ToInt32(tbsite.NoOfRemotes),
                              GateType = tbsite.GateType,
                              NoOfRacks = (tbsite.NoOfRacks == null) ? 0 : Convert.ToInt32(tbsite.NoOfRacks),
                            };

调用dc.tblSites.ToList()将从表中读取所有值和行。 如果要应用排序或过滤以减少读取的数据量,则需要在ToList()之前应用Where()OrderBy()调用

您收到该错误,因为EF将Select部分发送到服务器有两件事

1)可以直接使用dc.tblSites的对象。

2)如果您真的要转换它们,则首先从数据库中获取数据,然后创建对象.ToArray()是一个不错的选择。

... from tbsite in dc.tblSites.ToArray() ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM