如何处理TimeSpan以使用EF6将其保存在SQLite中 [英] How to handle TimeSpan to save it in SQLite with EF6

查看:93
本文介绍了如何处理TimeSpan以使用EF6将其保存在SQLite中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3个属性的模型:

I have a model that contains 3 properties:

public class SomeModel
{
    [Key]
    public int SomeInt { get; set; }

    public string SomeString { get; set; }

    public TimeSpan Time { get; set; }
}

如果我尝试将这样的模型添加到SQLite数据库中,则会引发异常.

If I try to add such a model to my SQLite Database an exception is thrown.

        using (var db = new MyDataContext())
        {
            var item = new SomeModel { SomeInt = 123, SomeString = "a string" , Time = new TimeSpan(1,2,3)};
            db.SomeModels.Add(item);
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
                throw;
            }
        }

例外:

System.NotSupportedException: "There is no store type corresponding to the EDM type 'Edm.Time' of primitive type 'Time'."

有什么方法可以将此模型添加到数据库中吗?

Is there any way to add this model to the database?

推荐答案

我建议使用整数代替 TimeSpan 字段,例如:

I suggest to use an integer instead of TimeSpan field, example:

public Int64 TimeSpanTicks{ get; set; }     

[NotMapped]
public TimeSpan Time 
{
    get { return TimeSpan.FromTicks(TimeSpanTicks); }
    set { TimeSpanTicks= value.Ticks; }
}

这篇关于如何处理TimeSpan以使用EF6将其保存在SQLite中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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