views:

35

answers:

1

I'd like to know if it is possible to map some database columns to a custom data type (a custom class) instead of the basic data types like string, int, and so on. I'll try to explain it better with a concrete example:

Lets say I have a table where one column contains (text) data in a special format (e.g a number followed by a separator character and then some arbitrary string). E.g. the table looks like this:

Table "MyData":

 ID |Title(NVARCHAR) |CustomData (NVARCHAR) 
 ---+----------------+-----------------------
 1  |Item1           |1:some text  
 2  |Item2           |333:another text  

(Assume I am not allowed to change the database) In my domain model I'd like to have this table represented by two classes, e.g. something like this:

public class MyData
{
  public int ID { get; set; }
  public string Title { get; set; }
  public CustomData { get; set; }
}
public class CustomData
{
  public int ID { get; set; }
  public string Text { get; set; }

  public string SerializeToString()
  {
    // returns the string as it is stored in the DB
    return string.Format("{0}:{1}", ID, Title);
  }
  public string DeserializeFromString(string value)
  {
    // sets properties from the string, e.g. "1:some text"
    // ...
  }
}

Does entity framework (V4) provide a way to create and use such "custom data types"?

A: 

No. Not like that, anyway.

However, you could work around this by:

  • Write a DB function to do the mapping and then use a defining query in SSDL.
  • Using one type for EF mapping and another type like you show above, and then projecting.
  • Add extension properties to your EF type to do this translation. You can't use these in L2E, but it may be convenient in other code.
Craig Stuntz