5

I'm creating a Database using the Microsoft Entity Framework and CodeFirst in C#. I want to use the Database in a WPF-Application, so the Entity-Classes should implement "INotifyPropertyChanged".

This can be done very elegantly using a PostSharp aspect, which triggers the PropertyChanged event automatically every time a property changes. If I create such an aspect and use it on my entity classes, I get the following exeption when trying to create the Database:

 \tSystem.Data.Entity.Edm.EdmNavigationProperty: Name: The specified name is not allowed:          '<Name>k__BackingField'.

Obviously PostSharp creates a property called "k__BackingField" which causes the database creation to fail, because it's an invalid name from the EntityFramework's point of view. Is there any way to circumvent this error without manually implementing "INotifyPropertyChanged" in every single Entity-Class?

P.S: English is not my native language, I would be very thankful if you informed me about possible mistakes in my postings.

Thank you in advance

BoltzmannBrain
  • 219
  • 2
  • 13
  • k__Backingfield is not generated bij postsharp but by the c# compiler when you use an auto implemented property. – albertjan May 13 '12 at 10:17
  • That may be true, but if I disable PostSharp the error no longer occurs. Somehow there has to be a relation between the error and PostSharp. – BoltzmannBrain May 13 '12 at 10:33
  • have you tried switching from an autoimplementedproperty to one with a backingfield? – albertjan May 13 '12 at 10:41
  • Actually that's what I wanted to circumvent by using PostSharp because there are a LOT of properties in our Entity Classes. If I create every single one with a backingfield, I can as well call "RaisePropertyChanged" in the setter instead of letting PostSharp do it for me. – BoltzmannBrain May 13 '12 at 10:45

1 Answers1

6

It's true that PostSharp can create a property called k__BackingField (the real name is a bit different; what you're seeing is the escapes name), because I suppose you're applying the aspect to fields, which causes PostSharp to encapsulate fields into properties of the same name. So, you can have a property named after the field.

You should check whether you really want to add the aspect to the field. Perhaps you just wanted to add the aspect to properties, but are adding it to fields by mistake. By default, LocationInterceptionAspects are applied (multicast) fo fields and properties. Use MulticastAttributeUsageAttribute.AttributeTargets to restrict it to properties.

Gael Fraiteur
  • 6,759
  • 2
  • 24
  • 31