我正在使用PC配置器應用程序,並且驗證有問題。應用程序的一點是要檢查主板上的插槽是一樣的CPU插座等實體框架驗證上下文 - null null測試中的異常
我做的代碼第一個數據庫使用Visual Studio 2013年的腳手架
public class Configuration : IValidatableObject
{
[Key]
public int ConfigurationID { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
[DisplayName("Configuration name")]
public string ConfigName { get; set; }
[ForeignKey("mb_id")]
public MotherBoard MotherBoard { get; set; }
[Column("mb_id", TypeName = "int")]
public Nullable<int> mb_id { get; set; }
[ForeignKey("cpu_id")]
public CPU CPU { get; set; }
[Column("cpu_id", TypeName = "int")]
public Nullable<int> cpu_id { get; set; }
}
這是在配置模型的一部分,我正在使用(其餘的看起來非常相似 - 只是其他組件)
我只是把這個模型腳手架控制器。
這是驗證的開始,它似乎是問題在這裏的某處(至少VS是這麼說的)。
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (MotherBoard == null) { throw new ArgumentNullException("Motherboard"); }
if (CPU == null) { throw new ArgumentNullException("CPU"); }
if (GPU == null) { throw new ArgumentNullException("GPU"); }
if (HDD == null) { throw new ArgumentNullException("HDD"); }
if (RAM == null) { throw new ArgumentNullException("RAM"); }
if (Power == null) { throw new ArgumentNullException("Power"); }
if (Case == null) { throw new ArgumentNullException("Case"); }
if (MotherBoard.CPU.ToUpper().Trim() != CPU.Socket.ToUpper().Trim())
{
yield return new ValidationResult("CPU socket does not match.", new[] { "cpu_id" });
}
}
當我創建沒有驗證的PC配置時,它通常會進入數據庫。但是,當我嘗試驗證它說,CPU(在空測試)爲空,並拋出空異常。 Screenshot from VS.
它永遠不會拋出它在主板上,但總是在下一個項目(第二項)。
您是否檢查CPU中的張貼值?它真的爲空,或者它拋出的異常不爲空 –
它實際上表現得很奇怪。當我將驗證放入評論中時,它通常會將配置放入數據庫中。但是當我取消註釋時,它表示主板爲空,但在CPU空測試中引發異常。 – healadin
我的意思是當我運行這個沒有驗證實現時,它創建配置與CPU和一切都沒有問題。 – healadin