数据契约强制从Web API帖子设置日期值

时间:2012-12-07 10:47:05

标签: asp.net-mvc json entity-framework angularjs

我有一个WepApi,它是从Angular / Json客户端调用的,它首先序列化为在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]

归因声明类型

CODE 模特

[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);
    }

0 个答案:

没有答案