views:

1329

answers:

2

I need to add a custom property to an Entity Framework class, however when I do I get the "The property name XXX specified for type XXX is not valid." error. Is there some attribute I can give the property so it is ignored and not mapped to anything?

Edit: If I add a custom property, as per Martin's example below, then the following code will raise the above error at the SaveChanges call.

MyEntities svc = new MyEntities(url);
MyEntity ent = new MyEntity();
ent.MyField = "Hello, world";
svc.AddMyEntity(ent);
svc.SaveChanges();
A: 

You can add a property in code:

public partial class MyEntity {
  public String MyCustomProperty {
    get;
    set;
  }
}

The Entity Framework generate partial classes enabling you to customize the generated class.

Also, to comment on your code I think should change it to something like this:

MyEntities svc = new MyEntities(url);
// Create MyEntity using the factory method.
MyEntity ent = MyEntities.CreateMyEntity(...);
ent.MyField = "Hello, world";
svc.AddMyEntity(ent);
svc.SaveChanges();

This will ensure that your entity is properly initialized.

Martin Liversage
That's what I have done but that would cause me to receive the above error when using the MyEntity class.
Sprintstar
Can you clarify when you get the error? During validation of you model, when you compile, or at run-time?
Martin Liversage
When I try to use the object to update the database, eg:MyEntities svc = new MyEntities(url);MyEntity ent = new MyEntity();ent.MyField = "Hello, world";svc.AddMyEntity(ent);svc.SaveChanges();I get an exception on SaveChanges.
Sprintstar