gpt4 book ai didi

c# - 使用 Entity Framework 保存组合框值时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:50 24 4
gpt4 key购买 nike

这个问题很简单,但我不明白为什么代码不起作用?

下面是我如何设置表单上 ComboBox 的成员:

private void LoadUsersToComboBox()
{
ScansEntities3 db = new ScansEntities3();

comboBox1.DataSource = db.People;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}

下面是我如何使用选定的成员:

private void CreateNewDepartment()
{
if ((textBox1.Text != String.Empty) && (comboBox1.SelectedIndex >= 0))
{
ScansEntities3 db = new ScansEntities3();
Department department = new Department()
{
Name = textBox1.Text,
Person = (Person)comboBox1.SelectedItem,
};
db.AddToDepartments(department);
db.SaveChanges();
}
}

我收到这个错误:

System.InvalidOperationException was unhandled
Message=An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.DataClasses.EntityObject.System.Data.Objects.DataClasses.IEntityWithChangeTracker.SetChangeTracker(IEntityChangeTracker changeTracker)
at System.Data.EntityUtil.SetChangeTrackerOntoEntity(Object entity, IEntityChangeTracker tracker)
at System.Data.Objects.ObjectStateManager.AddEntry(Object dataObject, EntityKey passedKey, EntitySet entitySet, String argumentName, Boolean isAdded)
at System.Data.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, Object entity, String argumentName)
at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at SQLite_Testing_Grounds.ScansEntities3.AddToDepartments(Department department) in C:\Users\Sergio.Tapia\documents\visual studio 2010\Projects\SQLite Testing Grounds\SQLite Testing Grounds\Model2.Designer.cs:line 89
at SQLite_Testing_Grounds.Form1.CreateNewDepartment() in C:\Users\Sergio.Tapia\documents\visual studio 2010\Projects\SQLite Testing Grounds\SQLite Testing Grounds\Form1.cs:line 64
at SQLite_Testing_Grounds.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\Sergio.Tapia\documents\visual studio 2010\Projects\SQLite Testing Grounds\SQLite Testing Grounds\Form1.cs:line 51
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at SQLite_Testing_Grounds.Program.Main() in C:\Users\Sergio.Tapia\documents\visual studio 2010\Projects\SQLite Testing Grounds\SQLite Testing Grounds\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

还有另一个问题可能导致此代码失败:

“名称”属性是一个字符串,这是预期的,因为它在数据库中就是这样。 'Person' 属性是 Department.Person 类型,在数据库中它是外键整数。

所以这是行不通的:

    private void CreateNewDepartment()
{
if ((textBox1.Text != String.Empty) && (comboBox1.SelectedIndex >= 0))
{
ScansEntities3 db = new ScansEntities3();
Department department = new Department()
{
Name = textBox1.Text,
Person = ((Person)comboBox1.SelectedItem).ID,
};
db.AddToDepartments(department);
db.SaveChanges();
}
}

最佳答案

我认为你必须处理你的 db。这里的问题是 SelectedItem 仍然附加到上下文。您可以使用上下文的 Detach() 方法将人员从上下文中分离出来,但我认为您真正的问题可能是您的代码应该如下所示:

private void LoadUsersToComboBox()
{
using (ScansEntities3 db = new ScansEntities3())
{
comboBox1.DataSource = db.People;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
}

如果这不能解决问题,请尝试以下操作:

private void LoadUsersToComboBox()
{
using (ScansEntities3 db = new ScansEntities3())
{
var people = db.People.ToList();

foreach (var person in people)
db.Detach(person);

comboBox1.DataSource = people;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
}

关于c# - 使用 Entity Framework 保存组合框值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4044128/

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