views:

178

answers:

2

I'm new to Linq to Sql, what I would like to achieve is to create a single read only property on the Entity class that is a combination of multiple fields, specifically I want to create a name field that combines- title, forename and surname.

I can see how to do it by changing the .designer.cs file but know I'm not supposed to touch that.

I'm attempting to do this so that in dynamic data I get a single column rather than multiple columns.

+4  A: 

The trick here is to use a partial class; create a new .cs file, and in the same namespace add a new class named for your type:

namespace My.Data.Namespace {
    partial class Employee {
        public string Foo {
            get {return Forename + " " + Surname; } // etc
        }
    }
}

This combines with the original (generated) class file. This is a common approach for adding additional functionality into generated entities (including the data-context). You might also want to look at "partial methods", since a number of partial methods are defined and used by LINQ-to-SQL.

One caveat: if your dbml is called MySystem.dbml, then avoid creating a MySystem.cs file (presumably for your partial classes); there is a bug in the code-generator that can cause this to fail. Just name it something else.

Marc Gravell
I've done that but in Dynamic data not seeing it appear in the grid that is constructed, Is there something else I need to do?
Nathan
Hmm... I don't know. If the property is available from your *other* code, then I wonder whether dynamic data is looking at the meta-model (rather than the type's properties). In which case it would be very hard to get it working. It might also simply be that dynamic data wants read/write properties... I don't know.
Marc Gravell
Found the answer. I needed to add [ScaffoldColumn(true)] attribute and now it appears in the grid. Lovely
Nathan
A: 

in your LINQ select statement, why don't you use something like:

select new {FullName = x.FirstName + " " + x.Surname};

Not sure if the syntax is 100% there but check out the idea.

FailBoy