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?
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?
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;}
}
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.