3

As a new to Entity Framework, and already having developed almost all classes with the ReadOnly collections, my question is:

Is there a way to use ReadOnly collections with Code First?

OR

Should ReadOnly collections be used with Code First?

Minnie
  • 257
  • 3
  • 16
  • For reference, there is a newer similar question with some interesting answers: https://stackoverflow.com/questions/11191103/entity-framework-read-only-collections – Bartosz Jun 29 '18 at 09:27

2 Answers2

3

Entity Framework supports Read Only Collections throught backing fields

There are conventions to folow: field must started with '_'. See field _posts in code bellow.

public class Blog
{
    public int BlogId { get; set; }

    private string _url;

    public string Url
    {
        get { return _url; }
        set { _url = value; }
    }

    //backing field
    private List<Post> _posts;

    public IReadOnlyList<Post> Posts => _posts.AsReadOnly();

}

public class Post{

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

} 
Anderson
  • 89
  • 3
1

No there is not way to use read only collections with EF because even during materialization of entities read from database EF must fill that collection with entities or assign writable collection to your navigation property.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thank you. For all I have read (and tried) about Code First that seemed to be the right answer, but I could not find any documentation on this. – Minnie Sep 19 '11 at 17:30
  • Actually I cannot give you any link now. I will try to search little bit but I 'm not aware of any now. – Ladislav Mrnka Sep 19 '11 at 19:21
  • Thank you, I have added the new question about documentation since I did not to want to broaden this question: [Documentation on ReadOnly Properties](http://stackoverflow.com/questions/7474867/entity-framework-code-first-documentation-on-readonly-properties) – Minnie Sep 19 '11 at 20:19
  • 2
    Then, how do you make Aggregate Roots to enforce the invariants in a Domain-Driven Design approach? This should be possible having EF to fill the "internal state" of the entity and then, the developer could expose it the way he wants. – SuperJMN Oct 13 '14 at 18:52