System.nullreferenceexception في نمط المستودع

برمجة


في نمط المستودع System.NullReferenceException
طريقة الحذف

System.NullReferenceException
HRResult=0x80004003
الرسالة = مرجع الكائن لم يتم تعيينه لمثيل كائن.
المصدر=Microsoft.EntityFrameworkCore
تتبع المكدس:
في Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.ValidateKeyPropertiesAndExtractCancellationToken(كائن[] keyValues، Boolean async، CancellationToken CancelToken)
في Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.Find (كائن[] القيم الأساسية)
في BL.Repositories.BaseRepository`1.GetById(Nullable`1 id) في E:\Programming\Folder\SoqRepository\BL\Repositories\BaseRepository.cs: السطر 51

ما حاولت:

فئة من قاعدة البيانات

ج #
using System;
using System.Collections.Generic;

namespace Sq.Models;

public partial class VwItem
{
    public string ItemName { get; set; } = null!;
    public decimal PurchasePrice { get; set; }
    public decimal SalesPrice { get; set; }
    public int CategoryId { get; set; }
    public string? ImageName { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; } = null!;
    public int CurrentState { get; set; }
    public string? UpdatedBy { get; set; }
    public DateTime? UpdatedDate { get; set; }
    public string? Description { get; set; }
    public string? Gpu { get; set; }
    public string? HardDisk { get; set; }
    public int? ItemTypeId { get; set; }
    public string? Processor { get; set; }
    public int? RamSize { get; set; }
    public string? ScreenReslution { get; set; }
    public string? ScreenSize { get; set; }
    public string? Weight { get; set; }
    public int? OsId { get; set; }
    public string CategoryName { get; set; } = null!;
    public string ItemTypeName { get; set; } = null!;
    public string OsName { get; set; } = null!;
    public int ItemId { get; set; }
}

واجهة الفصل

ج #
using Sq.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Interfaces
{
    public interface IBaseRepository <t> where T : class
    {
        public IEnumerable<t>GetAll();
        public IEnumerable<t> GetAll(Func<t, bool=""> Condition);
        public T GetById(int? id);
        public void Delete(T Entity);
        public void ChangeState(int id);
    }
}

ج #
using Domain.Interfaces;
using Sq.BL;
using Sq.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BL.Repositories
{
    public class BaseRepository<t> : IBaseRepository<t> where T : class
    {
        public LapShopContext LapShopContext;
        public BaseRepository(LapShopContext _LapShopContext)
        {
            LapShopContext = _LapShopContext ?? throw new ArgumentNullException(nameof(_LapShopContext));
        }

واجهة التنفيذ

ج #
using Sq.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Interfaces
{
    public interface IBaseRepository <t> where T : class
    {
        public T GetById(int? id);
        public void Delete(T Entity);
    }
}
        public T GetById(int? id)
        {
            try
            {
                return LapShopContext.Set<t>().Find(id);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public void Delete(T entity)
        {
            try
            {
                LapShopContext.Set<t>().Remove(entity);
                LapShopContext.SaveChanges();
            }
            catch (Exception)
            {
             return;
            }
        }

مراقب

ج #
public ActionResult Delete(int ItemId)
{
    if (ItemId == null)
    {

        return BadRequest("ItemId is null");
    }

    var Obj = baseRepository.GetById(ItemId);
    baseRepository.Delete(Obj);

    return RedirectToAction("List");
}

الحل 1

كرسالة خطأ، المشكلة تكمن في طريقة الحذف. تحاول طريقة الحذف إزالة كيان من السياق باستخدام LapShopContext.Set().Remove(entity). ومع ذلك، فإن الخطأ الذي تواجهه هو NullReferenceException، مما يشير إلى أن معلمة الكيان فارغة. قد تحدث المشكلة لأن أسلوب GetById يُرجع قيمة فارغة عند عدم العثور على المعرف المحدد، ولا تقوم بالتحقق من القيمة الخالية قبل استدعاء حذف. يمكنك تعديل رمز وحدة التحكم على النحو التالي:

ج #
public ActionResult Delete(int ItemId)
{
    if (ItemId == 0)
    {
        return BadRequest("ItemId is invalid");
    }
    var Obj = baseRepository.GetById(ItemId);
    if (Obj == null)
    {
        return NotFound($"Item with ID {ItemId} not found");
    }
    baseRepository.Delete(Obj);
    return RedirectToAction("List");
}

الحل 2

نظرًا لأن رمز المستودع الخاص بك يبتلع جميع الاستثناءات – وهي فكرة سيئة للغاية بالمناسبة! – السبب الوحيد أ NullReferenceException سيكون ذلك baseRepository يكون null.

تحقق من المُنشئ للتأكد من أنك قمت بتعيين الحقل بشكل صحيح، وقم بإلقاء استثناء إذا كانت القيمة التي قمت بتعيينها null:

ج #
public YourControler(IBaseRepository<YourItem> baseRepository)
{
    this.baseRepository = baseRepository ?? throw new ArgumentNullException(nameof(baseRepository));
}

أيضًا:

ج #
public ActionResult Delete(int ItemId)
{
    if (ItemId == null)

ان int لا يمكن أبدا أن يكون null. سيقوم المترجم بإنشاء ملف CS0472 تحذير على هذا الخط.

コメント

タイトルとURLをコピーしました