将实体框架用作DataGridView的数据源的正确方法是什么? [英] What is the correct way to use Entity Framework as datasource for DataGridView?

查看:99
本文介绍了将实体框架用作DataGridView的数据源的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过DataGridView Designer设置数据源,但未在其中列出,然后我通过向导生成了新的数据源,该向导生成了数据集。

I tried setting DataSource via DataGridView Designer but it wasn't listed there and then I generated new datasource via wizard which generated DataSet.

但是现在我的项目+ DataSet中有实体框架,我该如何只使用实体框架...我感到困惑。

But now I have Entity Framework in my project + DataSet how can I use Entity Framework only... I'm confused.

artiklBindingSource 是自动生成的,我只想将EF用作数据源,因为现在我陷入了不必要的数据集。

artiklBindingSource was automatically generated I only wanted to use EF as datasource now I'm stuck with unwanted DataSet.

推荐答案

添加要与 DataGridView DataGridView任务面板中,打开选择数据源:组合框,然后:

To add a data source to use with your DataGridView in DataGridView Tasks panel, open Choose Data Source: combo box and then:


  1. 单击添加项目数据源以打开数据源配置向导

  2. 中选择一个数据源类型选择对象,然后单击下一步

  3. 选择数据源对象中选择要添加到数据源的类,然后单击完成

  4. 它将为您的表单添加 BindingSource (用作 DataGridView DataSource ),您应该加载数据并将数据设置为 BindingSourc ,然后数据将显示在网格中。例如加载数据。

  1. Click Add Project Data Source to open Data Source Configuration Wizard.
  2. In Choose a Data Source Type Choose Object and click Next.
  3. In Select Data Source Objects choose class which you want to add to data source and click Finish.
  4. It will add a BindingSource to your Form which is used as DataSource of your DataGridView and you should load data and set data to DataSource of your BindingSourc and then data will be shown in your grid. For example to load data.

以下是代码示例:

using System;
using System.Windows.Forms;
using System.Data.Entity;
namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SampleDBEntities db;
        private void Form1_Load(object sender, EventArgs e)
        {
            db = new SampleDBEntities();
            db.Products.Load();
            this.productBindingSource.DataSource = db.Products.Local.ToBindingList();
        }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            db.SaveChanges();
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            db.Dispose();
        }
    }
}

这篇关于将实体框架用作DataGridView的数据源的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆