2017-07-11 18 views
0

我正在尝试使BlogId和Blog成为只读而不会丢失BlogId作为外键。我如何在EF Core 2.0中实现这一目标?由于如何在不丢失EF核心2.0中的外键的情况下执行只读属性?

public class Blog 
    { 
     public int Id { get; set; } 
     public string Url { get; set; } 
    } 

    public class Post 
    { 
     public int Id { get; set; } 
     public string Title { get; set; } 
     public string Content { get; set; } 

     private int _blogId; 
     public int BlogId =>_blogId; 

     //I want this entity to be read-only without loose the foreign key    
     //in the database 
     public Blog Blog { get; set; } 
    } 

    protected override void OnModelCreating(ModelBuilder modelBuilder)   
    { 
     modelBuilder.Property<int>("BlogId").HasField("_blogId"); 
    } 

回答

1

充分利用Blog属性的set访问protected

public Blog Blog { get; protected set; }

+0

感谢这个工作得很好。只是想知道,还有没有财产“设置”的另一种方式呢? – lgarcia11

+0

@ lgarcia11 EF需要在实现数据库值时设置属性的值,以便需要“set”访问器。 –

相关问题