Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "custom data types" with entity framework

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"?

like image 284
M4N Avatar asked Feb 23 '26 11:02

M4N


1 Answers

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.
like image 63
Craig Stuntz Avatar answered Feb 26 '26 00:02

Craig Stuntz