0

I am using ef core and mapster. I have some columns in my db that are nullable.

When I get them from the db, C# stores them as nulls(which makes sense). I want to return these fields are empty strings though when I send them back via my api.

public class CompanyDto
    {

        public string Website { get; set; }
    }


 public class Company
    {
        public int Id { get; set; }
        public string Website { get; set; } = "";
    }

company.Adapt<CompanyDto>()

what is the best way to make it so Website in the CompanyDto is an empty string.

chobo2
  • 83,322
  • 195
  • 530
  • 832

1 Answers1

0

Classic setter will do the job as well

public class Company
{
    public int Id { get; set; }

    private string _website;
    public string Website 
    { 
        get { return _website; }
        set { _website = value ?? string.Empty; }
    };

    public Company ()
    {
        _website = string.empty;
    }
}
Fabio
  • 31,528
  • 4
  • 33
  • 72
  • This did not seem to work, I put a breakpoint and it was never triggered, so maybe it being bypassed somehow. I moved the check to the get method and that will work. – chobo2 Jul 09 '18 at 21:41
  • Seems like mapster simply skip property if original value is null. You can set default value in constructor. – Fabio Jul 09 '18 at 23:22