实体框架代码First ReadOnly Collections

时间:2011-09-19 14:00:19

标签: entity-framework entity-framework-4.1 ef-code-first

作为Entity Framework的新手,已经开发了几乎所有带有ReadOnly集合的类,我的问题是:

有没有办法在Code First中使用ReadOnly集合?

OR

ReadOnly集合是否应与Code First一起使用?

2 个答案:

答案 0 :(得分:2)

没有办法在EF中使用只读集合,因为即使在从数据库EF读取的实体的实现过程中,也必须用实体填充该集合或将可写集合分配给导航属性。

答案 1 :(得分:0)

实体框架通过 backing fields

支持 只读集合

有以下约定:字段必须以“ _”开头。请参见下面的代码中的_posts字段。

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

}