Mapping protected properties in Entity Framework 4.1
I want to have a protected list in a class, accessible via methods. In this topic it's suggested that I could create a configuration class inside my model class, which I don't really like, but as long as it works.. So I have something along those lines:
public class Person
{
public int Id { set; get; }
public string Name { set; get; }
List<string> _address = new List<string>();
protected virtual ICollection<string> address { get { return this._address; } }
[NotMapped]
public string[] Address { get { return this.address.ToArray(); } } // I know it's not efficient.. I'll cache it.
public void AddAddress(string address)
{
// some business logic
this.address.Add(address);
}
public class OneMapping : EntityTypeConfiguration<Person>
{
public OneMapping()
{
this.HasMany(x => x.address);
}
}
}
and in db context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add<Person>(new Person.OneMapping());
base.OnModelCreating(modelBuilder);
}
The db context throws this exception when I'm trying to add an instance of person:
The navigation property 'address' is not a declared property on type 'Person'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.
So doesn't really work. Tried this sample: Mapping开发者_StackOverflow private properties with EF 4.1 Failed with same error.
Another solution would be to use ObservableCollection, and wire the business logic in events, but this logic doesn't need to run when objects are constructed by EF - only when they're constructed by user.. which isn't possible.
So I'm somewhat stuck here.. I hope someone out there already ran into this and solved it..
Thanks !
Your navigation property doesn't have setter so it cannot be mapped. All mapped properties must have accessible getter and setter because EF can assign them during entity materialization. That was true for EDMX where at least private setter was necessary but in case of code first it works even without setter.
Generally EF code first is not very good tool if you want to play with accessibility of mapped properties.
Edit:
Btw. Your address is not collection of entities but collection of strings - that is also not supported
精彩评论