Sipke Schoorstra
Sipke Schoorstra

Reputation: 3409

EF4 code first fluent mapping does not work with inherited properties?

Did anyone ever tried mapping an inherited property? Because I would be glad to hear that just works and that I am making a mistake somewhere, as I am getting the following error:

"The property 'UserName' is not a declared property on type 'Advertiser'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property. "

My model looks like this:

abstract class Entity { public int Id {get; set; }}
abstract class User : Entity { public string UserName {get; set;} }
sealed class Advertiser : User { }

My AdvertisementConfiguration class looks like this:

class AdvertiserConfiguration : EntityTypeConfiguration<Advertiser>
{
   public AdvertiserConfiguration()
   {
      // the following line indirectly causes an InvalidOperationException:
      Property( x => x.UserName ).HasMaxLength(50);
   }
}

If I change the Advertiser class so that it does not inherit from User (and pull the UserName property down) then everything works just fine.

Upvotes: 1

Views: 2448

Answers (1)

Slauma
Slauma

Reputation: 177133

You can (and in this case must) define a mapping for an abstract type:

class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        Property( x => x.UserName ).HasMaxLength(50);
    }
}

And then add it to the model builder configurations of course:

modelBuilder.Configurations.Add(new UserConfiguration());

User is an entity - abstract, but still an entity with all mapping options.

Upvotes: 9

Related Questions