3

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

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please elaborate on which of these options would work for an entity framework code-first approach? E.g., I can't find examples of using SSDL with code-first; what do you mean by projecting (do you mean having two properties, one which is the actual type and not stored in the DB and one stored in the DB that is casted/transformed to the desired type?) Thanks.
All of these will work with code-first. For "defining query," substitute DbDatabase.SqlQuery. Projecting is, well, projecting.

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.