SqlNullValueException:数据为空。无法在Null值上调用此方法或属性?

时间:2017-12-14 07:29:06

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

我使用点网核中的UseInMemoryDatabase测试以下网络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: Data is Null. This method or property cannot be called on Null values.
System.Data.SqlTypes.SqlBytes.get_Length()
Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter(Func getter, object target)
Microsoft.AspNetCore.Mvc.Internal.DefaultComplexObjectValidationStrategy+Enumerator.GetModel(object container, ModelMetadata property)
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 strategy)

1 个答案:

答案 0 :(得分:0)

我认为,您无法将参数检索为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;
}