lgarcia11
lgarcia11

Reputation: 59

How can I do a dependent entity read only without losing the foreign key in EF core 2.0?

I am trying to make BlogId and Blog read-only without losing BlogId as a foreign key. How can I achieve this in EF Core 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");
    }

Upvotes: 0

Views: 481

Answers (1)

Alaa Masoud
Alaa Masoud

Reputation: 7135

Make the Blog property's set accessor protected

public Blog Blog { get; protected set; }

Upvotes: 1

Related Questions