gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:53:45 25 4
gpt4 key购买 nike

工具:视觉工作室 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com