Reputation: 830
My situation is I'm working with a legacy database that has two traits that are common for most of the code - there are many values saved with fixed length that are padded with leading zeros, and also fixed length with trailing white space at the end. Very annoying to deal with, so I'm trying to figure out what the cleanest approach for formatting these values would be.
My main focus right now is on formatting the view models / dtos. I'm just querying the database with Dapper via queries or stored procedures, which get mapped to my DTO class, which gets served as Json through my webapi.
Right now this is what a lot of my model properties end up looking like:
public string PurchaseOrderNumber
{
get => _purchaseOrderNumber.TrimStart('0');
set => _purchaseOrderNumber = value;
}
This just ends up being repeated everywhere. It would be nice to be able to do something like this:
[TrimZeros]
public string SupplierName { get; set; }
I could aslo make a function that just does this in SQL, then make this a responsibility of all my sql queries/ stored procedures. This works when I'm using something light like Dapper, but not so much when I'm using Entity Framework.
Any recommendations on how to approach this?
Upvotes: 0
Views: 112
Reputation: 2940
You could use implicit casting and a helper class:
public class LegacyString
{
public string TrimmedValue {get; }
public LegacyString(string value)
{
this.TrimmedValue = value?.TrimStart('0');
}
public static implicit operator string(LegacyString legacy)
=> legacy?.TrimmedValue;
public static implicit operator LegacyString(string legacyValue)
=> new LegacyString(legacyValue);
public override string ToString() => this.TrimmedValue;
}
Then all you have to do in your main clasess is
public LegacyString PurchaseOrderNumber {get;set;}
and you can use it as if it was a string in an assignment
myObj.PurchaseOrderNumber = "00001345";
in an expression to get the value
string poNumber = myObj.PurchaseOrderNumber;
the only thing you'd lose is the ability to declare poNumber
as var
and expect it to be a string. But even then, if you use poNumber
where a string was expected the implict conversion would take care of it for you.
Upvotes: 1