问题描述
我正在学习使用Visual Studio,C#和Entity Framework Core,并且尝试创建WPF来编辑数据库中的条目。目前,我正在使用Adventureworks2014数据库。
我有一个Datagrid,它可以从我在Microsoft SQL Server Management中创建的视图中获取数据。
public void PopulateDataGrid()
{
using (var db = new Adventureworks2014Context())
{
DG1.ItemsSource = db.SmallView.ToList<SmallView>();
}
}
当我双击Datagrid中的条目时,我希望该应用程序打开一个新窗口,其中显示了该人的数据。我要根据复选框的状态使用其他视图
因此,我想选择一个人,获取该人的ID,然后在其他视图中使用该ID来获取我想要的数据。
这是我想出的(不起作用):
private void DG1DoubleClick(object sender,MouseButtonEventArgs e)
{
if (DG1.SelectedIndex != -1)
{
using (Adventureworks2014Context db = new Adventureworks2014Context())
{
SmallView smallView = (SmallView)DG1.SelectedItem; //getting the Data of a person
txtIdCreate.Text = Convert.ToString(smallView.BusinessEntityId); //just to check if i get an ID
NoAdminView noAdminView = new NoAdminView();
db.NoAdminView.FirstOrDefault(x => x.BusinessEntityId == smallView.BusinessEntityId);
TxtFirstName.Text = noAdminView.FirstName; //checking if i get anything from the other view
}
}
我的文本字段为空,因此我没有从视图中获得正确的引用。
我还可以将所有需要/将要使用的条目都使用不同的视图,并且可以仅显示特定的列,但这不是我尝试使用的方法,因为我认为当我能够“在视图之间切换”时,它真的很有用。当我想要的时候只有在需要时才使用带有很多列的较大视图。当我唯一需要做的就是更改ItemSource时,它也会非常有效。
当我在这里也错了时,很高兴知道为什么这种想法不正确。
很高兴收到一些反馈。 预先感谢您的宝贵时间。
解决方法
如果要使用EF-core从数据库获取数据。
我建议您可以先使用数据库。
首先,请安装以下nuget-package。
第二,请在软件包控制台中使用以下命令。
PM> Scaffold-DbContext "Server=server name;Database=AdventureWorks2014;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
第三,在生成名为Models
的文件夹之后,请在wpf应用程序中尝试以下代码。
public MainWindow()
{
InitializeComponent();
PopulateDataGrid();
}
public void PopulateDataGrid()
{
using (var db = new AdventureWorks2014Context())
{
var listentity = db.BusinessEntities.ToList<BusinessEntity>();
dataGrid1.ItemsSource = listentity;
}
}
private void dataGrid1_MouseDoubleClick(object sender,MouseButtonEventArgs e)
{
if (dataGrid1.SelectedIndex != -1)
{
using (AdventureWorks2014Context db = new AdventureWorks2014Context())
{
BusinessEntity entity = (BusinessEntity)dataGrid1.SelectedItem;
txtID.Text = Convert.ToString(entity.BusinessEntityId); //just to check if i get an ID
Person p= db.People.FirstOrDefault(x => x.BusinessEntityId == entity.BusinessEntityId);
txtFirstName.Text = p.FirstName; //checking if i get anything from the other view
}
}
}
结果: