Bob.at.Indigo.Health
Bob.at.Indigo.Health

Reputation: 11895

In EF Core, is it possible to store an entity attribute with an unrelated type?

I'm building an AspNet Core 2.1 website. My data model includes a Patient Class:

public class Patient
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

Now, I want my application code to deal with Name and DateOfBirth as string and DateTime respectively, but in the underlying table I want BOTH values stored as a string.

  1. Can someone point me to the specific data annotation attributes or Fluent API magic that lets me pap a POCO (Entity class) property to an UNRELATED database column type (i.e., map DateOfBirth to a string [NVARCHAR] database column), and

  2. Once I've got my database column correctly defined, does EF Core give me an extension point to easily insert my own code to translate between the POCO Type and the database column type?

Why would I want to do this (I hear you asking)? Because my website stores sensitive information, and am following the GDPR guidelines and implementing a pseudonymization scheme. The database table behind the Patient class doesn't store the actual data. Rather, it stores keys that identify the data in a separate "vault" database. My website has separate "vault" server with an API interface that stores key/value pairs. Access to the vault server is limited to authorized callers, and all accesses are logged.

So, I want to store the "keys" (strings) in the website database, and have some middleware that talks to the vault API to convert between actual values (from the vault) and keys (from the website database).

But, of course, I want the website code to be unaware of these middleware mechanics. The website code should see the POCO class properties as ordinary, strongly-typed members. All of the Type translation wants to be handled by the middleware.

Upvotes: 1

Views: 593

Answers (1)

Jan Paolo Go
Jan Paolo Go

Reputation: 6522

Use Value Conversions.

Value converters allow property values to be converted when reading from or writing to the database. This conversion can be from one value to another of the same type (for example, encrypting strings) or from a value of one type to a value of another type (for example, converting enum values to and from strings in the database.)

For example:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Patient>(builder => 
    {
        builder
            .Property(p => p.DateTime)
            .HasConversion(new DateTimeToStringConverter());
    });
}

Upvotes: 2

Related Questions