Reputation: 701
I'm coming across this reoccurring problem where I am working with a legacy database and linq to sql that uses the char datatype of a fixed length.
When I return the string it always has padding on the end and if I want to concat two strings in the select statement I always need to check if not null before doing so eg:
return (from person in personRepository.Get(p => p.FIRSTNAME.StartsWith(firstName)
|| p.SURNAME.StartsWith(surname) || p.DOB == dob)
select new PersonSearchModel
{
FullUserName = (person.SURNAME ?? "").Trim() + ", "
+ (person.FIRSTNAME ?? "").Trim() + " "
+ (person.MIDDLENAME ?? "").Trim()
}).ToList();
Is there a better approach? Can I have something in the database context to automatically trim strings?
Upvotes: 1
Views: 1055
Reputation: 701
I ended up changing the t4 template so that the classes generated auto trimmed strings if they were not null else they returned null.
public string Property(EdmProperty edmProperty)
{
string type = _typeMapper.GetTypeName(edmProperty.TypeUsage);
string propertyName = _code.Escape(edmProperty);
if(type == "string"){
return string.Format(
CultureInfo.InvariantCulture,
"private {1} _{6}; {5} \t{0} {1} {2} {{ {5}\t\t{3}get{{return _{6} == null ? null : _{6}.Trim();}} {5}\t\t{4}set{{ _{6} = value;}} }}",
Accessibility.ForProperty(edmProperty),
type,
propertyName,
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)),
Environment.NewLine,
propertyName.ToLower()
);
}else{
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
Accessibility.ForProperty(edmProperty),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
}
Upvotes: 1