在实体框架中正确使用PersianCalendar作为表列 [英] Correct way to use PersianCalendar as Table column in entity framework

查看:61
本文介绍了在实体框架中正确使用PersianCalendar作为表列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API项目,我试图在其中使用波斯历存储日期。这是我的POCO班级。

public class Person
{
    PersianCalendar p = new PersianCalendar();

    public Person()
    {

    }


    public Person(string firstName, string lastName, PersianCalendar birthDate)
    {
        FirstName = firstName;
        LastName = lastName;
        DateOfBirth = birthDate;
    }

    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public PersianCalendar DateOfBirth { get; set; }


}   

我为我的API创建了POST方法。

 public HttpResponseMessage Post([FromBody] Person _p)
    {
        try
        {
            db.Persons.Add(_p);
            db.SaveChanges();
            var msg = Request.CreateResponse(HttpStatusCode.Created,
                _p);
            msg.Headers.Location = new Uri(Request.RequestUri + _p.PersonId.ToString());
            return msg;
        }
        catch(Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }  

我正在使用Fiddler发送我的POST请求。

但在Chrome Dev工具中,我的Person类的断点出生日期设置为空。 有人能帮我解决哪里出了问题吗? 如何以波斯文格式发送日期?

推荐答案

您的模型POCO中的DateOfBirth不应该是PersianCalendar类型。日历用于操作DateTime对象,而不是作为DateTime对象的容器。

您的模型应将出生日期存储为正常DateTime,然后您可以使用PersianCalendar对其进行操作。简单(但有点难看)的方法是有一个DateTime字段和一个单独的公共string属性,用于获取和设置按波斯日历格式化的日期:

public class Person
{
    PersianCalendar p = new PersianCalendar();
    public Person()
    {

    }
    public Person(string firstName, string lastName, DateTime birthDate)
    {
        FirstName = firstName;
        LastName = lastName;
        DateOfBirth = birthDate;
    }
    public Person(string firstName, string lastName, string birthDateString)
    {
        FirstName = firstName;
        LastName = lastName;
        DateOfBirthString = birthDateString;
    }

    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public DateTime DateOfBirth;
    public string DateOfBirthString
    {
        get
        {
            return string.Format("{0}/{1}/{2}", p.GetYear(DateOfBirth), p.GetMonth(DateOfBirth), p.GetDayOfMonth(DateOfBirth));
        }
        set
        {
            var parts = value.Split('/');
            DateOfBirth = p.ToDateTime(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0, 0, 0, 0);
        }
    }
}
请记住,DateTime表示时间中的一般特定时刻。它没有任何唯一正确的字符串表示形式。但是,如果您使用与我上面的内容类似的内容,那么您可能会认为对于您的应用程序唯一正确的字符串表示是波斯日期,格式为yyyy/MM/dd


编辑:您还可以创建自定义JSONJsonConverter并在您的模型中使用它。然后,您的POCO模型可能如下所示:

public class Person
{
    public Person() { }
    public Person(string firstName, string lastName, DateTime birthDate)
    {
        FirstName = firstName;
        LastName = lastName;
        DateOfBirth = birthDate;
    }
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [JsonConverter(typeof(PersianDateConverter))]
    public DateTime DateOfBirth;
}

PersianDateConverter类如下所示:

public class PersianDateConverter : JsonConverter
{
    PersianCalendar pc = new PersianCalendar();
    public PersianDateConverter()
    {

    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string persianDateString = reader.Value as string;
        if (persianDateString == null)
            throw new ArgumentException("Error in PersionDateConverter.ReadJson: Got null string");

        var parts = persianDateString.Split('/');
        return pc.ToDateTime(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0, 0, 0, 0);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DateTime d = (DateTime)value;
        string output = string.Format("{0}/{1}/{2}", pc.GetYear(d), pc.GetMonth(d), pc.GetDayOfMonth(d));
        writer.WriteValue(output);
    }
    public override bool CanConvert(Type objectType)
    {
        if (objectType.Name == "DateTime")
            return true;
        return false;
    }
}

注意:此PersianDateConverter未针对边缘情况进行很好的测试。不过,只要它正在操作的数据是有效的,它似乎就可以正常工作。

这篇关于在实体框架中正确使用PersianCalendar作为表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆