【问题标题】:What is the correct way to use Entity Framework as datasource for DataGridView?使用实体框架作为 DataGridView 的数据源的正确方法是什么?
【发布时间】:2017-02-08 13:39:54
【问题描述】:

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

但是现在我的项目中有实体框架+数据集,我怎么能只使用实体框架...我很困惑。

artiklBindingSource 是自动生成的 我只想使用 EF 作为数据源,现在我被不需要的 DataSet 卡住了。

【问题讨论】:

    标签: c# .net winforms entity-framework datagridview


    【解决方案1】:

    要在 DataGridView 任务 面板中添加与 DataGridView 一起使用的数据源,请打开 选择数据源: 组合框,然后:

    1. 点击添加项目数据源打开数据源配置向导
    2. 选择数据源类型中选择对象并点击下一步
    3. Select Data Source Objects中选择要添加到数据源的类,然后点击Finish
    4. 它将添加一个 BindingSource 到您的 Form 中,用作您的 DataGridViewDataSource,您应该加载数据并将数据设置为 BindingSourcDataSource,然后数据将显示在您的网格中。例如加载数据。

    这是代码示例:

    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();
            }
        }
    }
    

    【讨论】:

    • 感谢您花时间回答,我一直选择数据库作为数据源而不是对象我想这可能是困扰我的事情......
    • 您可能还想只使用“ToList”而不是“ToBindingList”。对我来说运行得更快,并且无论如何都会在内部创建一个绑定列表。请参阅此 stackoverflow 答案以了解差异:stackoverflow.com/questions/2243950/…
    • 如何将过滤器应用于实体列表,例如按字段“ProductName”?
    • @Bull 你可能想看看this postthis one
    • 非常感谢你,礼萨!!已经看过这些帖子和其他帖子,并为自己找到了解决方案。竖起大拇指!!
    【解决方案2】:

    不知道这是不是最快的方法,但它更简单:

    dataGridViewStudents.DataSource = schoolContext.Students.ToList<Student>();
    

    【讨论】:

    • 它会起作用,但DbContext 无法以这种方式跟踪更改,您应该使用schoolContext.Students.Load(); dataGridViewStudents.DataSource = schoolContext.Students.Local.ToBindingList();
    猜你喜欢
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多