Add [IgnoreDataMemeber] to specific properties in a generated partial class
I have an Entity Framework POCO class that is generated by a T4 Template.
I am planning to use the generated class as my data contract. However, it has a few properties that don't need to be in the contract. For example I have a property called AddressId. It is the foreign key to the address table. Since the actual address is attached to the object I don't want the AddressId to be visible to the client.
I could modify the T4 template, but I would rather not.
I saw this post that showed how t开发者_Python百科o use 'MetadataType' to add attributes to existing properties in partial classes. This is the example that they gave:
[MetadataType(typeof(Dinner_Validation))]
public partial class Dinner {}
public class Dinner_Validation
{
[Required]
public string Title { get; set; }
}
But I tried that for my class (using [IgnoreDataMember]) and it does not work (the AddressId is still shown).
How can I hide this one property without having to make a whole new class to copy all my data into?
MetadataType works only with data annotations. It doesn't work with serialization attributes. Serialization attributes must be placed directly on properties in entity so if you want to use T4 template for class generation you must add logic for creating these attributes directly to template.
Edit:
If you want to build logic for generating special attributes you need somehow to tell T4 template which properties should be marked with the attribute. You can either hardcode such information into T4 template or you can put that information into EDMX file. EDMX file supports custom data elements in its XML structure. These custom XML elements can be latter used in T4 template for some additional logic. The only problem is that designer doesn't have support for that - you must add custom elements directly into EDMX opened as XML.
This whole is called Structural annotations. Some example with reverse processing (modifying database generation) can be found in my other answer (also check MSDN topic linked in the question). There is also whole extension project which perhaps allows adding new extensions together with designer support. I think you can also read about these customizations in Entity Framework 4 in Action book.
精彩评论