Определить источник ConstraintException в EF-сущности - PullRequest
0 голосов
/ 26 августа 2010

У меня есть класс сущностей со множеством ненулевых свойств строки.Если я попытаюсь установить для одного из них значение null, я получу ConstraintException и сообщение " Это свойство не может быть установлено в нулевое значение. "

Без настройкиПеременная трекера для имени каждого свойства перед присваиванием, есть ли способ, которым я могу определить, какое присваивание свойства вызвало исключение?

Ответы [ 2 ]

1 голос
/ 29 июля 2011

В стороне вашего класса POCO вы можете использовать шаблон проверки для этой проверки. Используйте инъекцию конструктора для необнуляемых свойств для внедрения.

public class Product:Entity<long>
{
    public Product(string description, string productNo, double? unitPrice, Category category)
    {           

       Check.Require(unitPrice.HasValue, "Unit price can not be null in Product");
       Check.Require(!string.IsNullOrEmpty(description),
              "Description can not be null in Product");            

        Check.Require(!string.IsNullOrEmpty(productNo), 
           "Product number can not be null in Product");

        Check.Require(category != null, "Category can not be null in Product");

        UnitPrice = unitPrice.Value;
        Description = description;
        ProductNumber = productNo;
        Category = category;
    }  



    /// <summary>
    /// Gets or sets the product id.
    /// </summary>
    /// <value>
    /// The product id.
    /// </value>
    public int ProductId { get; set; }

    /// <summary>
    /// Gets or sets the name.
    /// </summary>
    /// <value>
    /// The name.
    /// </value>
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the category id.
    /// </summary>
    /// <value>
    /// The category id.
    /// </value>
    public long CategoryId { get; set; }

    /// <summary>
    /// Gets or sets the category.
    /// </summary>
    /// <value>
    /// The category.
    /// </value>
    public Category Category { get; set; }

    /// <summary>
    /// Gets or sets the unit price.
    /// </summary>
    /// <value>
    /// The unit price.
    /// </value>
    public double UnitPrice
    {
        get; 
        set;
    }

    /// <summary>
    /// Gets or sets the description.
    /// </summary>
    /// <value>
    /// The description.
    /// </value>
    public String Description
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sets the product number.
    /// </summary>
    /// <value>
    /// The product number.
    /// </value>
    public string ProductNumber
    {
        get; 
        set;
    }
}

}

public class Check
{
       /// <summary>
    /// Requires the specified assertion.
    /// </summary>
    /// <param name="assertion">if set to <c>true</c> [assertion].</param>
    /// <param name="message">The message.</param>
    public static void Require(bool assertion, string message)
    {
        if(!assertion)
        {
            throw new PreConditionException(message);
        }
    }

    /// <summary>
    /// Ensures the specified assertion.
    /// </summary>
    /// <param name="assertion">if set to <c>true</c> [assertion].</param>
    /// <param name="message">The message.</param>
    public static void Ensure(bool assertion, string message)
    {
        if (!assertion)
        {
            throw new PostConditionException(message);
        }
    }
}

/// <summary>
/// Exception raised when a precondition fails.
/// </summary>
public class PreConditionException : Exception
{
    /// <summary>
    /// Initializes a new instance of the <see cref="PreConditionException"/> class.
    /// </summary>
    /// <param name="message">The message.</param>
    public PreConditionException(string message):base(message)
    {

    }
}

/// <summary>
/// Exception raised when a postcondition fails.
/// </summary>
public class PostConditionException:Exception
{
    /// <summary>
    /// Initializes a new instance of the <see cref="PostConditionException"/> class.
    /// </summary>
    /// <param name="message">The message.</param>
    public PostConditionException(string message):base(message)
    {

    }
}
0 голосов
/ 29 июля 2011

Можете ли вы получить доступ к трассировке стека? У него будет что-то вроде «MyEntity.set_MyNotNullableProperty42», в котором будет указано, какое свойство имеет значение null.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...