我可以修改此更好的方法并修复此错误

时间:2016-02-22 15:53:29

标签: entity-framework

这是我的代码

  using (var conn = new DataEntities())
            {
                var query = from c in conn.servers where c.Servername != null select c;
                servers srv = query.FirstOrDefault();
                if (srv != null)
                {
                    Start.IPAddress = srv.ServerIP;
                    Start.ServerName = srv.Servername;
                    Start.GamePort = Convert.ToUInt16(srv.ServerPort);
                }
                Start.Servers.Add(Start.ServerName, Start.GamePort);
            }

servers srv = query.FirstOrDefault(); //错误在这里

的未处理例外
type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll

Additional information: An error occurred while executing the command definition. See the inner exception for details.

可以写出通常更好的方法吗?

一些建议我还是初学者^^ 谢谢

1 个答案:

答案 0 :(得分:0)

解决

using (var conn = new DataEntities())
            {
                var query = from c in conn.servers
                            select new
                            {
                                c.Servername,
                                c.ServerPort,
                                c.ServerIP
                            };
                foreach (var item in query)
                {
                    Start.IPAddress = item.ServerIP;
                    Start.ServerName = item.Servername;
                    Start.GamePort = Convert.ToUInt16(item.ServerPort);
                }
                Start.Servers.Add(Start.ServerName, Start.GamePort);
            }