工具:视觉工作室 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
}
}
数据库图:
实体图:
附注:
最佳答案
您不应该像在 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/