Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 有效操作上的NullReferenceException_C#_Linq_Entity Framework - Fatal编程技术网

C# 有效操作上的NullReferenceException

C# 有效操作上的NullReferenceException,c#,linq,entity-framework,C#,Linq,Entity Framework,我需要从一个查询中获取我的ID(键入Guid): var firstQuery = from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0) join conts in myEntityContext.Cont on rooms.ID equals conts.ItemID select new { ContPrice = conts.Price, Roo

我需要从一个查询中获取我的ID(键入
Guid
):

var firstQuery = 
    from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0)
    join conts in myEntityContext.Cont on rooms.ID equals conts.ItemID
    select new
    {
        ContPrice = conts.Price,
        RoomPrice = rooms.Price
        IDs = rooms.ID
    };

foreach (var t in firstQuery)
{
    t.RoomPrice  = t.ContPrice;
}
然后我对它执行一些操作(更新价格),最后我使用ID进行第二次查询。第二个查询不包含这些ID。我以这种方式实现了这个问题:

var myIDs = firstQuery.Select(cr => cr.IDs).ToList();
我的第二个问题是:

var secondQuery = 
    from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0) 
    where !myIDs.Contains(rooms.fldID)                                   
    join conts in myEntityContext.Cont on rooms.ID equals conts.ItemID
    select new
    {
       RoomPrice = conts.fldPrice,
       IDs = rooms.ID
    };
当我在调试器模式下运行此代码并到达此行时:

var myIDs = firstQuery.Select(cr => cr.IDs).ToList();
…引发了一个异常:

NullReferenceException
对象引用未设置为对象的实例

它似乎与第二个查询有关,因为当我把第二个查询转换成一个单独的方法并将ID传递给它时,所有的东西都工作得很好,但是我不明白为什么它应该考虑变量初始化后写的一些查询。 整个守则是:

var calcDate = DateTime.Now.AddDays(-1);

var firstQuery = 
    from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0)
    join conts in myEntityContext.Cont on rooms.ID equals conts.ItemID
    where conts.date == calcDate
    select new
    {
        ContPrice = conts.Price,
        RoomPrice = rooms.Price
        IDs = rooms.ID
    };

foreach (var t in firstQuery)
{
    t.RoomPrice = t.ContPrice;
}

var myIDs = firstQuery.Select(cr => cr.IDs).ToList();


var secondQuery = 
    from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0) 
    where !myIDs.Contains(rooms.fldID)                                   
    join conts in myEntityContext.Cont on rooms.ID equals conts.ItemID
    where conts.date == calcDate && conts.Code = "01"
    select new
    {
       RoomPrice = conts.fldPrice,
       IDs = rooms.ID
    };

foreach (var t in secondQuery)
{
    ContPrice = Conts.Price,
    RoomPrice = Rooms.Price
}

myEntityContext.SaveChanges();
这是我的堆栈跟踪,如果有用的话:

Financial.UI.dll!Financial.UI.Services.Hotels.HotelServiceProxy.CalcProxy.DoCalc(System.DateTime calcDate) Line 5055 C# Financial.UI.dll!Financial.UI.Pages.Hotel.NightsCalculationPage.CallbackMethod_DoCalc() Line 65 + 0x37 bytes C# [Native to Managed Transition] Web.UI.dll!Web.UI.SystemCallback.ProcessCallback() Line 228 + 0x3b bytes C# Web.UI.dll!Web.UI.SystemCallbackHandler.ProcessRequest(System.Web.HttpContext context) Line 68 + 0x12 bytes C# System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() + 0x156 bytes System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously) + 0x46 bytes System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error) + 0x342 bytes System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb) + 0x60 bytes System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context) + 0xbb bytes System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) + 0x1f3 bytes System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) + 0x1f bytes [Native to Managed Transition] [Managed to Native Transition] System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) + 0x350 bytes System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) + 0x1f bytes [Appdomain Transition] Financial.UI.dll!Financial.UI.Services.HotelServiceProxy.CalcProxy.DoCalc(System.DateTime calcDate)行5055 C# Financial.UI.dll!Financial.UI.Pages.Hotel.NightsCalculationPage.CallbackMethod_DoCalc()行65+0x37字节C# [本机到托管转换] Web.UI.dll!Web.UI.SystemCallback.ProcessCallback()行228+0x3b字节C# Web.UI.dll!Web.UI.SystemCallbackHandler.ProcessRequest(System.Web.HttpContext上下文)第68行+0x12字节C# System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+0x156字节 System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep步骤,参考bool同步完成)+0x46字节 System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error)+0x342字节 System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext上下文,System.AsyncCallback cb)+0x60字节 System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr,System.Web.HttpContext上下文)+0xbb字节 System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr RootedObjectsInter、System.IntPtr nativeRequestContext、System.IntPtr moduleData、int标志)+0x1f3字节 System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr RootedObjectsInter、System.IntPtr nativeRequestContext、System.IntPtr moduleData、int标志)+0x1f字节 [本机到托管转换] [管理到本机转换] System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr RootedObjectsInter、System.IntPtr nativeRequestContext、System.IntPtr moduleData、int标志)+0x350字节 System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr RootedObjectsInter、System.IntPtr nativeRequestContext、System.IntPtr moduleData、int标志)+0x1f字节 [应用域转换]
我假设
var FirstQuery
解析为IEnumerable

您不能多次访问可枚举的
内容。

尝试在第一个查询中创建列表:

var FirstQuery = (from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0)                                    
    join Conts in myEntityContextt.Cont on rooms.ID equals Conts.ItemID
    select new
    {
        RoomPrice = Conts.fldPrice,
        IDs = rooms.ID
    }).ToList();

如果此行失败,则myEntityContext.Mark或myEntityContext.Cont可能是空对象

IDs IDs=rooms.ID可能获得空值

尝试添加以下内容: var myIDs=FirstQuery.ToList().Select(Cr=>Cr.IDs.ToList()

嗯,堆栈跟踪很有用:我假设您发布的代码位于
DoCalc()
方法中。但是,您发布的行不可能是代码中的第5055行:

var myIDs = firstQuery.Select(cr => cr.IDs).ToList();
若要在此行发生
NullReferenceException
,则
firstQuery
必须为null或
firstQuery.Select(cr=>cr.id)
必须返回null

但是,如果是这种情况,则在这两种情况下都会出现
ArgumentNullException
,而不是
NullReferenceException
。所以这不是错误所在


而且,你的代码不应该运行

例如,在下面的部分中,您应该会得到一个编译时错误:

foreach (var t in firstQuery)
{
    t.RoomPrice = t.ContPrice;
}
无法将属性或索引器“AnonymousType#1.RoomPrice”分配给--它是只读的

你想在这里做什么。。。我不知道:

foreach (var t in secondQuery)
{
    ContPrice = Conts.Price,
    RoomPrice = Rooms.Price
}

最有可能发生什么 您在
myEntityContext.Room
myEntityContext.Cont
中有一个
null
。查看他们的内容并验证这一点。如果您仍然不确定,当您获得异常时,请单击Visual Studio中的“将异常详细信息复制到剪贴板”(在异常窗口上),并将其粘贴到您的问题中。

var myIDs=new List();
var myIDs = new List<int>();
if( firstQuery.Count() > 0)
myIds =  firstQuery.Select(cr => cr.IDs).ToList();
if(firstQuery.Count()>0) myIds=firstQuery.Select(cr=>cr.IDs.ToList();
此代码无法编译。因此,假设它曾经编译过,并且您的所有房间和Cont都是实际的实例,其中没有空对象,那么可以使用匿名返回

试试这个

public class QueryResult
{
    public decimal ContPrice; //whatever your types are

    public decimal RoomPrice;

    public int IDs;
}
然后像这样使用它:

var firstQuery =
    from rooms in myEntityContext.Room.Where(t => t.fldClosed == 0)
    join conts in myEntityContext.Cont on rooms.ID equals conts.ItemID
    where conts.date == calcDate
    select new QueryResult
                {
                    ContPrice = conts.Price,
                    RoomPrice = rooms.Price,
                    IDs = rooms.ID
                };

var firstQueryResult = firstQuery.ToList();

foreach (var t in firstQueryResult)
{
    t.RoomPrice = t.ContPrice;
}
正如其他人所说,避免多次列举

同时删除第二个查询并最初获得第一个工作。。。你对第二个有一些问题。首先,结果又是匿名类型。这是一种滥用,因为它们应该在linq之间使用;您应该解析为强类型。第二,

",conts.Code=“01”

不编译,应为:

conts.Code.Equals("01")
我还建议您将查询分解为更小的部分;也许是这样的

var roomsOpenQuery = myEntityContext.Room.Where(t => t.fldClosed == 0);
var roomsOpenQueryResolved = roomsOpenQuery.ToList();
var contQuery = myEntityContext.Cont
    .Where(t => roomsOpenQueryResolved.Any(r => r.ID == t.ItemID))
    .Where(x => x.date == calcDate);


var availableRooms =
    contQuery
        .Join(roomsOpenQueryResolved,
                c => c.ItemID,
                r => r.ID,
                (c, r) => new AvailableRoom()
                            {
                                ContPrice = c.Price,
                                RoomPrice = r.Price,
                                IDs = c.ItemID
                            })
        .ToList();


//Price Adjustment etc...

为什么没有任何评论就投了反对票?也许一个完整的框架可以help@MaryamArshi在出现异常情况时,您确实需要向我们提供。否则我们帮不了你。我怀疑例外情况是否发生在您指定的行中。还有一个堆栈跟踪字符串,可以从VisualStudio中抛出的
异常中获取。只需复制并添加到您的帖子中。@MaryamArshi您仍然应该发布