2017-12-14 161 views
0

ドットネットコアにUseInMemoryDatabaseを使用して、次のWeb APIコードをテストしています。SqlNullValueException:データがNullです。このメソッドまたはプロパティをNull値で呼び出すことはできませんか?

コントローラ

[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) 
+0

私はpがnullだと思います。この 'if(p!= null && p.Passcode == 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; 
} 
関連する問題