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

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

问题描述

我尝试通过 DataGridView Designer 设置 DataSource,但它没有在那里列出,然后我通过生成 DataSet 的向导生成了新的数据源.

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 任务 面板,打开 Choose Data Source: 组合框,然后:

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. Select Data Source Objects 中选择要添加到数据源的类,然后单击Finish.
  4. 它会添加一个 BindingSource 到你的 Form 中,它被用作 DataGridViewDataSource,你应该加载数据并将数据设置为 BindingSourcDataSource,然后数据将显示在您的网格中.例如加载数据.
  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();
        }
    }
}

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

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