views:

69

answers:

3

Is there a way I can have a generated code file like so:

public partial class A {
public string a {get; set;}
}

and then in another file:

public partial class A {
[Attribute("etc")]
public string a {get; set;}
}

So that I can have a class generated from the database and then use a non-generated file to mark it up?

A: 

If I understand your question correctly, then the answer is yes. I use this when I have a MVC project using LINQ2SQL and I write "buddy classes" to implement field validation code in the partial class.

public class foo
{
    public string FirstName { get; set; }
}

public partial class foo
{
    [Required(ErrorMessage = "This is a required field.")]
    public string FirstName { get; set; }
}
Andy Evans
What do you mean by "buddy" classes? How is your non-partial associated with the partial version?
Kirk Woll
A: 

Not as such; the compiler will complain that the member is defined in multiple parts. However, as the use of custom attributes is reflective in nature, you could define a "metadata" class and use it to contain decorators.

public class A
{
   public string MyString;
}

public class AMeta
{
   [TheAttribute("etc")]
   public object MyString;
}

...

var myA = new A();
var metaType = Type.GetType(myA.GetType().Name + "Meta");
var attributesOfMyString = metaType.GetMember("MyString").GetCustomAttributes();
KeithS
How often is it that the actor who is adding the attributes to his or her properties is also the person consuming them and will therefore know to look for the magical "Meta" classes?
Kirk Woll
Quite often, in my experience. This wouldn't work for an existing aspect-oriented framework, but if you were decorating your domain with, say, custom validation attributes, you're the one looking for them and can define where. My team has done exactly this on one of our projects. The main disadvantage is not looking for the other class; it's maintaining two parallel classes while developing, one functional, the other decorative. That would be a problem in partial classes as well, if you were able to define partial fields/properties in the first place.
KeithS
A: 

I've seen something like this done in an article by Scott Guthrie (near the end of it) - didn't try it myself, though.
http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

alt text

Dan Dumitru
This answer bears mentioning, but it is not a general solution to the question posed by the OP. Consumers of the attributes still need to know to look for the meta data class -- i.e. these attributes will *not* be returned by Attribute.GetCustomAttribute(...). (Fortunately for many use-cases, the consumers are written by MS and in certain situations this will work.)
Kirk Woll