Search code examples
c#linq-to-sqldynamic-data

Can I combine fields via Linq to Sql


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.


Solution

  • 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.