如何使用公共只读属性

时间:2017-12-27 22:51:31

标签: ef-core-2.0

System.NotSupportedException:Collection是只读的。 在System.ThrowHelper.ThrowNotSupportedException(ExceptionResource资源) 在Microsoft.EntityFrameworkCore.Metadata.Internal.ClrICollectionAccessor`3.Add(对象实例,对象值)    at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.AddToCollection(InternalEntityEntry entry,INavigation navigation,IClrCollectionAccessor collectionAccessor,Object value)

public class Student 
{
     public int Id {get; private set;}
     private List<StudentProgress> _progresses;
     protected Student()
     {
        _progresses = new List<StudentProgress>();
     }
    public IEnumerable<StudentProgress> Progresses =>_progresses.AsReadOnly();
}

public class StudentProgress 
{
    public int Id {get; private set;}
    public int ProgressStatusId { get; private set; }
    public int Year { get; private set; }
    public Grade Grade { get; private set; }
    public int CourseId { get; private set; }

    public StudentProgress(Grade grade, int year, int courseId, int progress)
    {
        ProgressStatusId = progress;
        Year = year;
        Grade = grade;
        CourseId = courseId;
    }
}

public class StudentEntityTypeConfiguration : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> studentConfiguration)
    {
        studentConfiguration.HasKey(x => x.Id);
        studentConfiguration.Ignore(x => x.DomainEvents);

      studentConfiguration.Metadata.FindNavigation(nameof(Student.Progresses))
        .SetPropertyAccessMode(PropertyAccessMode.Field);
    }
}

public class Context : DbContext
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ApplyConfiguration(new StudentEntityTypeConfiguration());
    }
}

这是我收到错误的地方(存储库):

public async Task<Student> FindAsync(int identity)
{
    var student = await _context.Set<Student>()
        .Include(x=>x.Progresses) // this line is generating the error
        .Where(b => b.Id == identity)
        .SingleOrDefaultAsync();

        return student;
}

1 个答案:

答案 0 :(得分:0)

我尝试更改您在代码中获取_progresses的方式:

public class Student 
{
     public int Id {get; private set;}
     private List<StudentProgress> _progresses;
     protected Student()
     {
        _progresses = new List<StudentProgress>();
     }
    public IEnumerable<StudentProgress> Progresses =>_progresses; // changed from AsReadOnly()
}