Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim values using Linq to Sql?

Tags:

c#

linq-to-sql

In the database, I have a table called Contact. The first name and other such string fields are designed to use a Char datatype (not my database design). My object Contact maps to a string type in the properties. If I wanted to do a simple test retrieving a Contact object by id, I would do something like this:

Contact contact = db.Contacts.Single(c => c.Id == myId);
Contact test = new Contact();
test.FirstName = "Martin";

Assert.AreEqual(test.FirstName, contact.FirstName);

The contact.FirstName value is "Martin " because of the char type. Where can I intercept the FirstName property when it is being loaded? OnFirstNameChanging(string value) does not get called on the initial load (contact), but does on the test object.

like image 515
Marsharks Avatar asked Mar 16 '09 20:03

Marsharks


1 Answers

Maybe you could put it in the OnLoaded() partial method? Note: I've never used this, but I assume it would look like this:

public partial class Contact
{
    partial void OnLoaded()
    {
        FirstName = FirstName.Trim();
    }
}
like image 146
Chris Shaffer Avatar answered Sep 18 '22 15:09

Chris Shaffer