为什么我的数据不在db.SaveChanges()上更新?

时间:2014-07-24 15:22:06

标签: c# data-binding entity-framework-5

这是我的代码:

using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace BookExample
{
    public partial class Form1 : Form
    {
        private readonly BooksContext db = new BooksContext();

        public Form1()
        {
            this.InitializeComponent();
            this.LoadBooks();
        }

        private void LoadBooks()
        {
            var books = from book in this.db.Books
                        orderby book.Author.Name
                        select new BookProjection { Title = book.Title, AuthorName = book.Author.Name, Price = book.Price };

            var booksList = new BindingList<BookProjection>(books.ToList());
            bindingSource1.DataSource = booksList;
            this.dataGridView1.DataSource = bindingSource1;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            this.db.SaveChanges();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.LoadBooks();
        }
    }

    public class BookProjection
    {
        public string AuthorName { get; set; }
        public decimal Price { get; set; }
        public string Title { get; set; }
    }
}

以下是表单的内容:

enter image description here

这是模型的样子:

enter image description here

以下是我的表格定义:

CREATE TABLE [dbo].[Books] (
[BookId]   INT             IDENTITY (1, 1) NOT NULL,
[Title]    VARCHAR (50)    NOT NULL,
[AuthorId] INT             NOT NULL,
[Price]    DECIMAL (18, 2) NOT NULL,
PRIMARY KEY CLUSTERED ([BookId] ASC)
);   

CREATE TABLE [dbo].[Authors] (
[AuthorId] INT          IDENTITY (1, 1) NOT NULL,
[Name]     VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([AuthorId] ASC)
);

程序显示数据正常。我可以编辑显示的数据。例如,弗兰克赫伯特的名字被错误拼写为#34;弗拉克&#34;。当我更正拼写并点击更新按钮时,db.SaveChanges()被调用(我在调试中看到了确定),但数据库永远不会被更新。我假设我没有正确设置程序中的数据绑定。有人可以就检查什么给我一些建议吗?

1 个答案:

答案 0 :(得分:0)

因为这行

        var books = from book in this.db.Books
                    orderby book.Author.Name
                    select new BookProjection { Title = book.Title, AuthorName = book.Author.Name, Price = book.Price };

...具体为select new BookProjection - 当您为每个Book对象创建新实例时,您已将参考丢失回db.Books DbSet

绑定到绑定列表中的Books DbSet(您仍然可以控制数据网格设置中显示哪些列),或者您必须存储Books集合的副本在Form1课程中,使用List<BookProjection>的{​​{1}}更改手动更新。{/ p>