首页 > 解决方案 > 如何在 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- 和控制器。

标签: c#asp.netasp.net-mvc

解决方案


问题

你得到 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());

这种方法称为构造函数注入,它是依赖注入方法之一。


推荐阅读