1

I have a class with some string properties that represent dates in an arbitrary format. These need to remain as String properties. Is there a way, using the fluent API or something, to indicate that these column types should be datetime. And then somehow I can tell EF to marshal the data in a certain way?

Can I just use:

HasColumnType("datetime")

and if so, how would I then handle the marshalling?

Example Class:

public Class SomePOCO{

    public String SomeTimeInWierdFormat { get; set; }
    public String SomeOtherTimeInWierdFormat { get; set; }
    public String SomeString{ get; set; }
}

Is there a string format that I can massage these strings into that would allow me use HasColumnType("datetime") without any complaints?

8
  • 1
    why you want to keep the property as string ? Commented Jun 12, 2013 at 15:27
  • Lets just say it has to be that way, I have no control over that. Commented Jun 12, 2013 at 15:29
  • 1
    Then why can't you store them as strings in DB as well and then convert them to dates on output? Commented Jun 12, 2013 at 15:31
  • 1
    there has to be a better way. "I want a datetime to store a string" is silly/ridiculous. Commented Jun 12, 2013 at 15:33
  • 1
    If it needs to be a string is some other layer of the application, I suggest you keep it as a DateTime on your entity, and use a DTO/ViewModel/Whatever to make it a String. Commented Jun 12, 2013 at 15:37

1 Answer 1

2

You can use read only properties to expose your DateTimes as formatted strings. This is useful because way you can still have properties that correctly map to the database while exposing that data however you choose. Maybe something like this:

public Class SomePOCO{

    public DateTime DateTimeColumn { get; set; }
    public string DateTimeColumnAsString { get { return this.DateTimeColumn.ToString(); } }

}
Sign up to request clarification or add additional context in comments.

3 Comments

It should probably be marked as not mapped so that EF doesn't persist the string.
Is that necessary since DateTimeColumnAsString doesn't have a setter?
It seems to make sense that there would be a convention for that, but I would have to try to see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.