Currently I use Entity Framework code first to create my domain models. As the code below illustrates, I want create a one-to-many association between "Test2" class and "Test1" class. But when I ran the application, it threw an exception:
The navigation property 'T2' is not a declared property on type 'Test1'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.
If I modify the navigation property "T2" to make it have a "protected" or public setter. It is OK. So it seems that the Entity framework does not support the readonly navigation properties. Could anyone explain and give some links for this problem?
public abstract class Test1Base
{
public int Id {get; set}
public virtual Test2 T2 {get; private set;}
}
public class Test1 : Test1Base
{
}
public class Test2
{
public int Id {get; set;}
public string Name {get; set;}
}
public class MyDbContext : DbContext
{
public DbSet<Test1> Test1Table {get; set;}
public DbSet<Test2> Test2Table {get; set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Test1>().HasRequired(t => t.T2).WithMany();
}
}