How to tell entity framework how to save instances of a custom type (that can be stored as a scalar)

StackOverflow https://stackoverflow.com/questions/9451000

  •  13-11-2019
  •  | 
  •  

Question

One of my entity classes would be possible to store in a sql server database as a BIGINT. My question is: How do I get a Entity Framework context to know how to store and retrieve instances of my entity class?

More detail. I'm using Noda Time, which can represent a (much) wider range of dates than can SQL or .NET datetime (AND it's a dessert topping). My Entity Class, Happening, is a wrapper around NodaTime's Instant class. I can set a Happening from a long, and get a long from a happening with methods like .SetFromLong(long instant) and .ToLong().

Currently I have my model working, saving classes that contain properties of the dot net DateTime type. If instead I want to use properties of my custom type "Happening", how do I tell Entity Framework how to save those?

If I'm reading this article about Modeling and Mapping am I on the right track or missing something simpler?

http://msdn.microsoft.com/en-us/library/bb896343.aspx

I'm using entity framework 4.

Was it helpful?

Solution

What i recommend doing is adding 2 properties on your entity a NodaTime and a long, and exclude your NodaTime property using [NotMapped] in your EF model, then in your getter/setter update the long.

ie

public class MyEntity{
   public long TimeAsLong{get;set;}
   [NotMapped]
   public Happening {
      get{
        return new Happening().SetFromLong(TimeAsLong);
      }
      set {
         TimeAsLong = value.ToLong();
      }
   }
}

The effect of this will be that the long is stored in the db but you can access it on the class via NodaTime

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top