Does the Entity Framework code first support readonly navigation property

谁都会走 提交于 2019-12-10 15:44:23

问题


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.



来源:https://stackoverflow.com/questions/10268062/does-the-entity-framework-code-first-support-readonly-navigation-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!