Friday, 28 September 2012

How to create the DataContracts and Translators for Entity Framework generated objects

Think I've just come up with a fool proof method for creating datacontracts and associated translator logic from Entity Framework generated objects

Creating datacontracts

1. Grab the class definition from the xxxModel.cs file in xxxx.DataContracts.csproj project

2. Paste into a new file in the xxx.DataContracts namespace

3. Use Resharper to clean up the code (Ctrl +E , Ctrl + C), choose full format option

4. Suspend off Resharper (Tools, options ,Resharper)

5. Grab the primitives section and change privates to publics

6. Replace ; with { get; set; } and then replace _ with empty string

7. That's it, you now have your matching datacontract with no typos and property names matching the auto generated ones in the xxxModel.cs file.

Creating translators (little bit more involved) method

1. Use the following regex replace expression on the pasted properties from the class you created above.

Remember to paste them from the datatype definition onwards, and put them at the start of the line in the mapping class first! e.g.

String Author { get; set; }
String DMlibraryName { get; set; }
DateTime? DateCreated { get; set; }
String DocNAME { get; set; }
int? DocNumber { get; set; }
String DocPath { get; set; }
String DocTypeCode { get; set; }
String DocTypeDescription { get; set; }
Int32 IsDMType { get; set; }
Int32 IsRRAKMANType { get; set; }
int? PersonID { get; set; }
int? ProjectID { get; set; }
String ProjectLabel { get; set; }
String htmlLocation { get; set; }

Find: ^([a-zA-Z_$][a-zA-Z0-9_$?]*):b{(.*)}\{(.*)
Replace with: source.\1 = dest.\1;

Result is as follows...

source.Author  = document.Author;
source.DMlibraryName  = document.DMlibraryName;
source.DateCreated  = document.DateCreated;
source.DocNAME  = document.DocNAME;
source.DocNumber  = document.DocNumber;
source.DocPath  = document.DocPath;
source.DocTypeCode  = document.DocTypeCode;
source.DocTypeDescription  = document.DocTypeDescription;
source.IsDMType  = document.IsDMType;
source.IsRRAKMANType  = document.IsRRAKMANType;
source.PersonID  = document.PersonID;
source.ProjectID  = document.ProjectID;
source.ProjectLabel  = document.ProjectLabel;
source.htmlLocation  = document.htmlLocation;

(Old Creating translators (little bit more involved) method)

1. Turn resharper back on

2. Use the File Structure window

clip_image001

3. Stick this in Excel and do some manipulation (ask me if you're not sure how to do this)

clip_image002

4. Paste this back into your C# file, and do a regex replace of \t with nothing

5. That's it, translator code written

No comments:

Post a Comment

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...