【发布时间】:2018-01-29 23:23:17
【问题描述】:
在我的 C#/WPF 应用程序中,我有一个 ListView 控件,我填充如下:
private void Load()
{
DbSet<recordHistory> recordHistory = _db.recordHistories;
var query = from cbHistory in recordHistory
orderby cbHistory.id descending
select new { cbHistory.id, cbHistory.Content, cbHistory.Size, cbHistory.DateAdded };
crRecordHistoryList.ItemsSource = query.ToList();
}
上述工作按预期工作。我的ListView 控件填充了来自 SQL 数据库的所有已保存记录。
当我开始调试应用程序时,它按预期执行。但是,当我选择其中一个 ListView 项目(无论我选择哪个项目)并单击 Remove 按钮时,只有第一条记录会从数据库和 ListView 控件中删除。
预期行为是将 selected 记录从数据库和列表视图控件中删除...
我的Remove 方法
private void Button_Remove_Click(object sender, RoutedEventArgs e)
{
foreach (var record in _db.recordHistories.Local.ToList())
{
Console.WriteLine("Removing Record Id:" + record.id);
_db.recordHistories.Remove(record);
}
_db.SaveChanges();
this.crRecordHistoryList.Items.Refresh();
this.Load();
}
此外,所有后续项目选择和单击删除按钮都不会从数据库/列表视图控件中删除任何内容)
我还在Remove 方法中尝试了以下方法(只是为了获取 ID):
Console.WriteLine("Removing Record Id:" + (crRecordHistoryList.SelectedItem as recordHistory).id);
在这种情况下,我得到:
System.NullReferenceException: '对象引用未设置为对象的实例。'
我的recordHistory 班级(自动生成)
using System;
using System.Collections.Generic;
public partial class recordHistory
{
public int id { get; set; }
public string Content { get; set; }
public string Size { get; set; }
public Nullable<int> DateAdded { get; set; }
}
编辑:我已经弄清楚为什么它只删除了第一条记录,然后没有其他任何事情发生(无论选择了哪个项目)......这是因为从Local 获取记录(在我的foreach 语句中),我应该简单地拥有以下内容---这是我最初的尝试,试图将ID输出到Console:
private void Button_Remove_Click(object sender, RoutedEventArgs e)
{
recordHistory testRecord = new recordHistory();
testRecord.id = (recordHistory)crRecordHistoryList.SelectedItem;
_db.recordHistories.Attach(testRecord);
_db.recordHistories.Remove(testRecord);
_db.SaveChanges();
this.crRecordHistoryList.Items.Refresh();
this.Load();
}
但是,下面一行
testRecord.id = (recordHistory)crRecordHistoryList.SelectedItem;
正在抛出错误:
无法将类型“recordHistory”隐式转换为“int”
顺便说一句:如果我将第二行替换为:testRecord.id = 85;,上述内容将完美运行。
因此,我尝试将上述行更改为以下内容,但无济于事:
testRecord.id = System.Convert.ToInt32(crRecordHistoryList.SelectedItem);
任何想法如何删除选定的记录?
【问题讨论】:
-
crRecordHistoryList.SelectedItem是一种匿名类型(object--将鼠标悬停在您的query变量上,您将看到可枚举的静态类型)。您无法将recordHistory转换为int,因为您尝试将对象转换为recordHistory,然后尝试将that 分配给id,即int。select new recordHistory {...}在您的 linq 语句中或者至少对于视图模型类而不是匿名类型怎么样。然后你就可以访问强类型的属性了。 -
@pinkfloydx33 谢谢!您的评论为我指明了进一步研究的方向,结果是一个已解决的问题(我已经发布了我的解决方案),以及在路上学习更多——我绝对欢迎正确的(或者,只是“更好” ) 方法,如果有的话(作为 C#/WPF 新手,我确信有:))
标签: c# wpf entity-framework