EF, How to save/retrieve TimeSpan as other data type?

折月煮酒 提交于 2019-12-11 08:35:49

问题


SQLCe doesn't support TimeSpan, so I need to save this in some other way. Is it possible to define somewhere a default conversion, like in the DbContext, or would I need to handle this manually in the repositories? I don't like to change my entity classes just because of this.

Btw, I only save TimeSpan of < 24h.

Example would be great if there are some neat tricks.


回答1:


I know you say you don't want to modify your entities, but if you're using code first this would be pretty simple to do by modifying your entities :)

You could define a property that isn't mapped into the database, that uses another property as its backing store. In this example, TickCount would get saved in the database, but everything else could access Span which exposes TickCount as a TimeSpan struct.

public long TickCount { get; set; }

[NotMapped]
public TimeSpan Span { 
    get { 
        return new TimeSpan(TickCount); 
    } 
    set { 
        TickCount = value.Ticks; 
    } 
}



回答2:


Pretty old but in case anyone ever needs this, I have cloned and modified System.Data.SQLite in order to support TimeSpan properties (mapped to sqlite TIME columns) You can find the source at https://github.com/arielflashner/System.Data.SQLite




回答3:


Well, it seems this is basically NOT POSSIBLE.

A TimeSpan property must be marked NotMapped, or by fluent Ignore (then saved as per Steve's answer). At least that's my understanding now.

EF does not support type mapping or type conversion.. https://stackoverflow.com/a/12053328

Btw, NHibernate maps TimeSpan to integer by default, when using SqLite. No conversions or tricks needed there. Not sure about other databases.



来源:https://stackoverflow.com/questions/18472961/ef-how-to-save-retrieve-timespan-as-other-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!