【发布时间】:2012-03-10 21:28:12
【问题描述】:
我有一个服务方法,可以非常简单地获取数据库中所有商店的信息。它使用 Auto Mapper 从 EF 映射存储,并返回 StoreDTO 类型的通用响应(一个简单的 POCO)。
问题是这样的:方法执行得很好,我一直走到最后。 response 中的每个属性都有一个值,没有什么是 null。列表中填充了项目,列表中的项目是有效的,等等。
但以下代码会在 GetAllStores 返回时立即抛出 NullReferenceException:
ListResponseDTO<StoreDTO> allStores = Services.Stores.Stores.GetAllStores();
编辑:这是调试器的屏幕截图,就在它返回时。您可以在监视窗口中看到这些值看起来很干净:http://i.imgur.com/rd853.png
非常感谢任何帮助。以下是该方法的代码:
public static ListResponseDTO<StoreDTO> GetAllStores()
{
ListResponseDTO<StoreDTO> response = new ListResponseDTO<StoreDTO>("Get Stores not successful");
try
{
response.Items = new List<StoreDTO>();
using (DomainEntities db = new DomainEntities(Global.ConnectionString))
{
foreach (var IndividualStore in db.Stores)
{
Mapper.CreateMap<Store, StoreDTO>();
var IndividualStoreDTO = Mapper.Map<Store, StoreDTO>(IndividualStore);
response.Items.Add(IndividualStoreDTO);
}
}
response.Message = "Store(s) retrieved successfully";
response.Success = true;
}
catch (Exception ex)
{
Logging.Log("Get All Stores", response.Message + " " + ex.ToString(), Logging.LogPriority.Error, "Store Operations");
}
return response;
}
这是通用 DTO 定义:
public class ListResponseDTO<DtoType> : ResponseDTO
{
public ListResponseDTO()
: base()
{
Items = new List<DtoType>();
}
public ListResponseDTO(string defaultMessage)
: base(defaultMessage)
{
Items = new List<DtoType>();
}
public List<DtoType> Items;
}
如果您想知道,ResponseDTO 有两个属性:
bool Success
string Message
这里是异常详情,恐怕没有太大帮助:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=Infinity
StackTrace:
at PLM.Infinity.Default.GetDrawersForUser() in C:\Users\jlucas\Documents\Visual Studio 2010\PLM Source Control\Utilities\InfinityInterface\Infinity\Default.aspx.cs:line 96
InnerException:
【问题讨论】:
-
尝试删除 try/catch 看看会发生什么
-
@DJKRAZE:
GetAllStores方法是代码的第二个 sn-p。 -
你能发布异常的完整堆栈跟踪吗?
-
你能显示更多关于你打电话给
Services.Stores.Stores.GetAllStores()的上下文吗?堆栈跟踪是否在内部异常中有任何内容,或者它实际上是在哪里停止的? -
大概
GetDrawersForUser()是ListResponseDTO<StoreDTO> allStores = Services.Stores.Stores.GetAllStores();行的方法吧?另外,我假设从您的屏幕截图中,当您单击该点时,它会返回到父级,这是它立即抛出错误的时候?是否有机会看到更多GetDrawersForUser()方法以了解它是否与您的调用方式有关?
标签: c# entity-framework automapper nullreferenceexception dto