Additional attributes

Additional attributes

Postby Alladin » Wed 07 Apr 2010 17:05

Hi there,

I need to add [Key] property attribute to some of the LINQ to SQL classes (System.ComponentModel.DataAnnotations.KeyAttribute).

However MyModel.Designer.cs is getting overwritten every time I made changes to the model.

Is there some workarounds to inject custom property attributes or *.tt file to customize source code generator?

Thank you in advance,
Lex
Alladin
 
Posts: 149
Joined: Mon 27 Nov 2006 16:18

Postby AndreyR » Thu 08 Apr 2010 14:38

The simplest way to add custom attribute is to add it to the DataContext.cs class. It is designed to contain custom attributes and properties which should not be affected by the rebuilding of the project.
Add the attribute and the partial class declaration to this file in the following way:
Code: Select all
[System.ComponentModel.DataAnnotations.Key]
  public partial class MyClass{
  }
AndreyR
Devart Team
 
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Re: Additional attributes

Postby Alladin » Thu 08 Apr 2010 16:26

Your example shows how to add custom class attributes.

Alladin wrote:I need to add [Key] property attribute
Alladin
 
Posts: 149
Joined: Mon 27 Nov 2006 16:18

Postby AndreyR » Fri 09 Apr 2010 11:54

In this case you will need a bit more complicated approach.
Create a new code generation template (Tools->Entity Developer->Templates->New...), and load the code from the LINQ C# template.
Add the following code
Code: Select all
        if(property.Name == "MyProperty")#>
        [System.ComponentModel.DataAnnotations.Key]
<#+;

to the GenerateProperty method after the following lines:
Code: Select all
        if (property.UpdateCheck != LinqUpdateCheck.Always) {
          #>, UpdateCheck = UpdateCheck.<#= property.UpdateCheck #><#+
        }
        #>)]
<#+

Set the model template to the one we have just created (Model Properties->Template) and the code generation will generate the Key attibute for the MyProperty property.
AndreyR
Devart Team
 
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Postby Alladin » Fri 09 Apr 2010 14:25

Big thanks / Большое спасибо

:roll:
Alladin
 
Posts: 149
Joined: Mon 27 Nov 2006 16:18

Postby Alladin » Fri 09 Apr 2010 14:46

Found a bug in LINQ 2 SQL template:

this code line is always generated:

Code: Select all
private static System.Data.Linq.Mapping.MappingSource mappingSource = new Devart.Data.Linq.Mapping.AttributeMappingSource();


However, if I choose to store mapping in file, mappingSource should be XmlMappingSource.
Alladin
 
Posts: 149
Joined: Mon 27 Nov 2006 16:18

Postby AndreyR » Tue 13 Apr 2010 11:36

Thank you for the report, this issue is associated with the problems in MappingMode=File.
It will be fixed in one of the nearest builds.
AndreyR
Devart Team
 
Posts: 2919
Joined: Mon 07 Jul 2008 13:16


Return to LinqConnect (LINQ to SQL support)