1

I have a WCF service.

I have a field (say Name) and now client wants to change this into FirstName (first half before a space) and LastName (everything after a space).

This WCF service is being used by different applications and I want to accomplish this without breaking any existing clients.

Can I add two new datamember even though they are not exists in the database? How the value will be set or get for these two new datamembers?

Thanks

Tippu
  • 1,191
  • 4
  • 16
  • 36
  • 3
    Bear in mind this is a pretty hard thing to do correctly. What if someone has a space in their last name like `Mark Van Duser` or goes by initials `E. F. Codd`? – JNK Apr 11 '12 at 15:06
  • Yup, or what if you have someone who only has one name, like quite a few footballers from africa... You might want to check if there is a space before trying to split by it, and then think about if you want it in FirstName or SecondName – Mikey Mouse Apr 11 '12 at 15:15

2 Answers2

5

Something like this should work:

DECLARE @FullName VARCHAR(255)
SET @FullName = 'James Johnson'

SELECT SUBSTRING(@FullName, 1, CHARINDEX(' ', @FullName) - 1) AS FirstName,
       SUBSTRING(@FullName, CHARINDEX(' ', @FullName) + 1, LEN(@FullName)) AS LastName

The output from the above looks like this:

FirstName    LastName
------------ ----------------
John         Doe

To parse the name in code, the code example below should work fine for first and last names. If you need a robust parser that can handle prefixes, suffixes, and middle names take a look at this article.

var names = ("James Johnson").Split(Convert.ToChar(" "));
if (names.Length > 0)  
    Response.Write(string.Format("First: {0}, Last: {1}", names[0], names[1]));
James Johnson
  • 45,496
  • 8
  • 73
  • 110
1

If the new data members are strings then this should be fine, the additional data members will be ignored by older versions of the service client.

See this related question: Adding field to WCF data contract breaks clients?

Community
  • 1
  • 1
DaveRead
  • 3,371
  • 1
  • 21
  • 24
  • Adding the column should be fine, but how about the retrieving the data. I have the following datamember [DataMember] public string Name { get; set; }. How will I add the two new datamember now? – Tippu Apr 11 '12 at 15:14
  • Add them as [DataMember] public string FirstName { get; set; }, [DataMember] public string Surname { get; set; } (or similar) and then update your data access layer to populate accordingly. – DaveRead Apr 11 '12 at 15:17