簡體   English   中英

為什么我的數據沒有在db.SaveChanges()上更新?

[英]Why isn't my data updating on db.SaveChanges()?

這是我的代碼:

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

表單如下所示:

在此處輸入圖片說明

該模型如下所示:

在此處輸入圖片說明

這是我的表定義:

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

該程序可以很好地顯示數據。 我可以編輯顯示的數據。 例如,弗蘭克·赫伯特(Frank Herbert)的名字拼寫為“ Frack”。 當我糾正拼寫並單擊“更新”按鈕時,將調用db.SaveChanges() (我肯定在調試中進行了監視),但從未更新數據庫。 我假設我在程序中的數據綁定設置不正確。 有人可以給我一些檢查建議嗎?

因為這條線

  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(您仍然可以控制在數據網格的設置中顯示哪些列),要么必須在Form1類上存儲Books集合的副本並使用List<BookProjection>手動更新List<BookProjection>BindingList更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM