1

我有一个从 Angular/Json 客户端调用的 WepApi,它首先序列化为在 EF 代码中创建的模型。我想发布产品模型并在 post/save 函数中设置 changedate 属性。我得到 ModelState.IsValid = false,是否有任何解决方法我想保留我的 ef 模型属性

[Required]  
public DateTime ChangeDate { get; set; }

得到这个错误托盘张贴

{"$id":"1","Message":"发生错误。","ExceptionMessage":"类型 'Entity.Product' 上的属性 'ChangeDate' 无效。值类型的属性标记为 [必需]还必须用 [DataMember(IsRequired=true)] 标记才能被识别为必需的。考虑使用 [DataContract] 赋予声明类型

代码模型

[DataContract]
public class Product
{
    public Product()
    {
        ChangeDate = DateTime.Now;
    }

    //Serialization
    [DataMember]
    //DataAnnotations
    [DisplayName("ProductId")]
    [Description("ProductId")]
    public int ProductId { get; set; }

    //Serialization
    [DataMember(IsRequired = true)]
    //DataAnnotations
    [DisplayName("ChangeDate")]
    [Description("Date when product last was changed")]
    [Required]
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime ChangeDate { get; set; }

    //Serialization
    [DataMember]
    //DataAnnotations
    [DisplayName("Name")]
    [Description("Name")]
    [Required(ErrorMessage = " ")]
    [StringLength(100)]
    public String Name { get; set; } 


    public HttpResponseMessage Post(Entity.Product product,Boolean directSave = true)
    {
        if (ModelState.IsValid)
        {
            product.ChangeDate = DateTime.Now;
            _productRepository.Add(product);
            if (directSave)
                _context.Save();

            var response = Request.CreateResponse(HttpStatusCode.Created, product);
            response.Headers.Location = GetLocation(product.ProductId);
            return response;
        }

        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
4

0 回答 0