【问题标题】:SqlNullValueException: Data is Null. This method or property cannot be called on Null values?SqlNullValueException:数据为空。不能在 Null 值上调用此方法或属性?
【发布时间】:2020-06-13 02:43:08
【问题描述】:

我正在 dot net core 中使用 UseInMemoryDatabase 测试以下 Web api 代码。

控制器

    [HttpGet("{id}", Name = "GetPasscode")]
    public IActionResult GetPasscode(SqlBytes id)
    {
        if (id == null) 
        {
            throw new ArgumentException("Invalid address");
        }
        var p = _context.AddressPasscodes.FirstOrDefault(a => a.Address == id);
        if  (p == null) 
        {
            p = new AddressPasscode{ Address = id, Passcode = 123 };
            _context.AddressPasscodes.Add(p);
            _context.SaveChanges();
        };
        return new ObjectResult(p);
    }

型号

public class AddressPasscode
{
    public SqlBytes Address { get; set; }
    public int Passcode { get; set; }
}

但是,在测试http://localhost:5000/api/passcode/1时出现如下运行时异常

SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
System.Data.SqlTypes.SqlBytes.get_Length()
SqlNullValueException:数据为空。不能对 Null 值调用此方法或属性。 System.Data.SqlTypes.SqlBytes.get_Length() Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter(Func getter,对象目标) Microsoft.AspNetCore.Mvc.Internal.DefaultComplexObjectValidationStrategy+Enumerator.GetModel(对象容器,ModelMetadata 属性) Microsoft.AspNetCore.Mvc.Internal.DefaultComplexObjectValidationStrategy+Enumerator+c__DisplayClass10_0.b__1() Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationEntry.get_Model() Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitChildren(IValidationStrategy 策略)

【问题讨论】:

  • 我认为 p 是空的。使用这个if (p != null && p.Passcode == 0)

标签: asp.net asp.net-web-api .net-core


【解决方案1】:

我认为,您无法将参数检索为SqlBytes。也许,您可以将其获取为string 并转换为SqlBytes 类型。

[HttpGet("{id}", Name = "GetPasscode")]
public int GetPasscode(string id)
{
    var sqlBytes = new SqlBytes(Encoding.UTF8.GetBytes(id));
    var p = _context.AddressPasscodes.FirstOrDefault(a => a.Address == sqlBytes);
    if  (p.Passcode == 0) 
    {
        _context.AddressPasscodes.Add(new AddressPasscode{ Address = sqlBytes, Passcode = 123 });
        _context.SaveChanges();
    };
    return p.Passcode;
}

【讨论】:

    猜你喜欢
    • 2012-03-31
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多