visual-studio-2010 - 被 "The EntityCollection has already been initialized."错误卡住

标签 visual-studio-2010 entity-framework entity-framework-4 ado.net-entity-data-model

工具:视觉工作室 2010
语言: C#

我刚刚开始学习 Entity Framework ,我遇到了一个问题,每当我使用 Code#1 时它都可以正常工作,但是每当我使用 CODE#2 时,我都会出错(发布在下面)

Title: InvalidOperationException was unhandled by user code
Error Message "The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph."


//SchoolModel.Designer.cs
public EntityCollection<Course> Courses
{
    get
    {  //Blah blah code }
    set
    {
        if ((value != null))
        {//Below statement is pointed by Visual Studio as Exception Thrower
            ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Course>("SchoolModel.CourseInstructor", "Course", value);
        }
    }
}

代码# 1:
List<string> list = new List<string>();
var prs = new Person();
using (var myEntity = new SchoolEntities())
{
    var result = myEntity.People;
    foreach (var ppl in result)
    {
        list.Add(ppl.PersonID+","+ppl.FirstMidName);
    }
}

代码# 2:
List<string> list = new List<string>();
List<Person> prsList = new List<Person>();//when using this list,problem started
var prs = new Person();
using (var myEntity = new SchoolEntities())
{
    var result = myEntity.People;
    foreach (var ppl in result)
    {
        list.Add(ppl.PersonID+","+ppl.FirstMidName);

        //New code which raised exceptions
        prs.PersonID = ppl.PersonID;
        prs.FirstMidName = ppl.FirstMidName;
        prs.LastName = ppl.LastName;
        prs.Courses = ppl.Courses;
        prsList.Add(prs);
        //New code end
    }
}

数据库图:
Database Diagram from tutorial

实体图:
enter image description here

附注:
  • 我在 http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-3 上关注了 EF 教程,然后偏离并开始玩它:)
  • 我确实找到了一些相关的错误问题,但我的情况不同。
  • 最佳答案

    您不应该像在 prs.Courses = ppl.Courses 中那样设置 EntityCollection .该集合已被初始化(根据异常(exception)情况)。您只能通过 Add 修改它ing Course实例。

    关于visual-studio-2010 - 被 "The EntityCollection has already been initialized."错误卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9766048/

    相关文章:

    asp.net - self 跟踪实体与POCO实体

    asp.net - 无法在 Web 服务器上启动调试。启动的 URL 的 IIS 工作进程当前未运行

    c# - 将变量从 C# 传递到 Powershell

    linq - 关于 Entity Framework ,Var vs IEnumerable

    entity-framework-4 - Entity Framework (4.0)-使用外键添加新记录

    visual-studio-2010 - EF4 和连接字符串

    visual-studio-2010 - Visual Studio 2010 模糊字体

    c++ - 为什么编译器会向 lib 添加内联类方法?

    entity-framework - 如何判断上下文中是否有任何实体使用.Net Entity Framework 4.0

    c# - 在 Visual Studio 2015 中使用 ADO.NET 和 MySQL