3

Suppose I have an Contact Table in my database, with a PhoneNumber column, which is a string, "+44123456789", for example.

In my domain model, I would normally have:

public class Contact {
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
}

So far so ordinary :) But now, I want to associate a bunch of non-DB logic with my PhoneNumber.

I can make a PhoneNumber object to hold all that logic, and make my PhoneNumber property be a Number object instead:

public class Contact {
    public int Id { get; set; }
    public Number PhoneNumber { get; set; }
}
public class Number{
    public string Number { get; set; }
    //... other logic, getter wrappers, etc. ...
}

But EF is going to interpret that as "Number is a new type with a separate table, and the Contact object should have a FK to a row in the Number table". Which I don't want - I want to keep the DB model the same. I can just do the conversion manually, in my C# but it's going to end up with a lot of boilerplate.

I would like to be able to tell EF, "I know this looks like an object, but trust me, it's a primitive. When you're storing it in the database, it's actually a primitive column. Please convert it to and from the primitive in the appropriate way (provided by the Number class, if necessary) whenever you interact with the database.

Does this concept exist in EF?

If so, what is the correct search term to find documentation of this?

Interested to know in either EF or EFCore.

Brondahl
  • 7,402
  • 5
  • 45
  • 74
  • +44.. you cant type to number. But this is what you want? https://stackoverflow.com/questions/14812557/how-to-map-column-and-entity-propery-of-different-datatypes-in-entity-framework – daremachine Jan 26 '19 at 09:16
  • or this https://stackoverflow.com/questions/9613421/map-a-dictionary-in-entity-framework-code-first-approach – daremachine Jan 26 '19 at 09:19
  • 2
    Looks like you are seeking for EF6 [Complex Type](https://entityframework.net/complex-type). The similar (but not exact) concept in EF Core is [Owned Entity Type](https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities) – Ivan Stoev Jan 26 '19 at 10:36
  • @IvanStoev Yup, that's exactly the one. Do you want to post that as an answer, so that I can Accept it? – Brondahl Jan 26 '19 at 10:58

1 Answers1

2

Answer, courtesy of Ivan Stoev (See comments on question):

Looks like the search term you are looking for is "Complex Type" in EF6.

Example search result: https://entityframework.net/complex-type

In EFCore, a similar (but not identical) concept is "Owned Entity Type".

Example search result: https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities

Brondahl
  • 7,402
  • 5
  • 45
  • 74