c# - 如何在 C# 中比较两个 GUID 值(一个来自数据库,一个在“if”语句中手动编码)?
问题描述
我已经在表 dbo.Integrations 中手动编码了值,其中一列 IntegrationId="907BC4CF-4DC0-41FB-8EA4-87FE73A5BAE3"。我正在尝试比较 Guid 值以返回一个函数。
但我得到这个错误:
System.NullReferenceException:“对象引用未设置为对象的实例。” mcniDbC 为空。
我的代码是:
/****************************************************************************************************************
* File Name : IntegrationsProcessor.cs
* Description : This class is used for doing all Integration related database operation.
* Created By : Anirudh Singh Rawat
* Created Date : 6 April 2016
****************************************************************************************************************/
#region Namespace
using DBModel;
using MCNIDev.DBAccess;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web.Mvc;
using Utilities;
#endregion
namespace MCNIDev.Processor.Services
{
public class IntegrationsProcessor
{
#region Private Member
private MCNIDbContext mcniDbC;
#endregion
#region Public Methods
/// <summary>
/// This method is used for getting the existing
/// data from Integrations table.
/// </summary>
public Integration GetIntegrationRow()
{
return mcniDbC.Integration.FirstOrDefault(e => e.IntegrationId == Guid.Parse("907BC4CF-4DC0-41FB-8EA4-87FE73A5BAE3"));
}
#endregion
}
}
这是导致错误的代码行:
return mcniDbC.Integration.FirstOrDefault(e => e.IntegrationId == Guid.Parse("907BC4CF-4DC0-41FB-8EA4-87FE73A5BAE3"));
DbContext
请不要在这种情况下通过将它与文件松散耦合来使用此类对数据库执行操作MCNIDbContext
- 和控制器。
解决方案
问题
你得到 NullReferenceException 因为你没有为mcniDbC
.
private MCNIDbContext mcniDbC;
您声明它但您没有分配,因此默认情况下它是null
.
解决方案:构造函数注入
您可以创建一个构造函数来分配mcniDbC
.
namespace MCNIDev.Processor.Services
{
public class IntegrationsProcessor
{
#region Private Member
private MCNIDbContext mcniDbC;
#endregion
public IntegrationsProcessor(MCNIDbContext context)
{
mcniDbC = context;
}
...
}
}
接下来,在您的主程序中,您实例化IntegrationsProcessor
如下:
var integrationProcessor = new IntegrationsProcessor(new MCNIDbContext());
这种方法称为构造函数注入,它是依赖注入方法之一。
推荐阅读
- python - python3.0 的 concat() 备用组
- angular - 如何将动态 HTML 标记传递给引导模式?
- python - Can I get a warning always evaluates to true in Python?
- git - csv 输出中 cloc 空白、注释、代码的总和
- python - 我希望能够使用日期找到特定的数据
- java - 重新抛出异常真实应用
- amazon-web-services - 在组织中使用 AWS Codecommit
- javascript - 在打印 div 内容时,它占用空间和空白页
- angular - “ionic cordova run android”给出了奇怪的未知错误 Ionic 2
- selenium - 是否可以使用需要 2FA 的电子邮件自动化测试用例?