Does the Entity Framework code first support reado

2019-06-26 09:12发布

问题:

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();
    }
}

回答1:

It is probably some minor limitation in code first which is not caused by a private setter but by the private setter in the base class and mapping of the derived class. If you move the T2 declaration from Test1Base to Test1 it will work with private setter but if you want to leave it in Test1Base make the setter protected.