Can I combine fields via Linq to Sql
-
10-07-2019 - |
Question
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.
OTHER TIPS
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.