Can the EF Core mapping be overriden to change the type of data from the database to my model?

Viewed 34

My model has a column that's of type, HierarchyId. I want this to be a string instead. When I change the property type to string, it's unable to automatically convert that type to a string. Is there a way to override the mapping so I can manually convert it to a string?

This is how I am performing the query:

public List<T> GetData<T>(int startIndex, int batchSize) where T : class
{
    var models = new List<T>();
    var dbSet = _context.Set<T>();

    var data = dbSet.Skip(startIndex).Take(batchSize);

    foreach (var item in data as IEnumerable)
    {
        //Converts the deserialized item to the generic model type that was passed in
        var model = (T)Convert.ChangeType(item, typeof(T));
        models.Add(model);
    }

    return models;
}

The error I get happens when I try to loop through the data. This error shows it converting to a byte. I was just trying different things:

Unable to cast object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize

enter image description here

1 Answers
modelBuilder.Entity<Project_Task>()
            .Property(p => p.Outliner)
            .HasConversion<HierarchyIdConverter>();

public class HierarchyIdConverter : ValueConverter<string, HierarchyId>
{
    public HierarchyIdConverter()
        : base(
            v => HierarchyId.Parse(v),
            v => v.ToString())
    {
    }
}

It was a little confusing because the order of the types and conversions were flipped. But this worked.

Related