您的位置:首页 > 博客中心 > 数据库 >

WPF 数据绑定 使用Code First with Database

时间:2022-03-13 22:38

一、准备工作

1.开发工具 Visual Studio 2013

2.安装Code First with Database

3.创建示例数据库 MyShop

gxlsystem.com,布布扣gxlsystem.com,布布扣
USE MyShop
GO

CREATE TABLE [dbo].[Categories]
(
  [CategoryId] [INT] NOT NULL IDENTITY ,
  [Name] [NVARCHAR](MAX) ,
  CONSTRAINT [PK_dbo.Categories] PRIMARY KEY ( [CategoryId] )
) 
 
CREATE TABLE [dbo].[Products]
(
  [ProductId] [INT] NOT NULL
                    IDENTITY ,
  [Name] [NVARCHAR](MAX) ,
  [CategoryId] [INT] NOT NULL ,
  CONSTRAINT [PK_dbo.Products] PRIMARY KEY ( [ProductId] )
) 
 
CREATE INDEX [IX_CategoryId] ON [dbo].[Products]([CategoryId]) 
 
ALTER TABLE [dbo].[Products] 
ADD CONSTRAINT [FK_dbo.Products_dbo.Categories_CategoryId] 
FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[Categories] ([CategoryId]) 
ON DELETE CASCADE
GO

INSERT INTO dbo.Categories ( Name ) VALUES( N‘水果‘ )
INSERT INTO dbo.Categories ( Name ) VALUES( N‘肉类‘ )
GO

INSERT INTO dbo.Products ( Name, CategoryId ) VALUES  ( N‘苹果‘, 1)
INSERT INTO dbo.Products ( Name, CategoryId ) VALUES  ( N‘菠萝‘, 1)
INSERT INTO dbo.Products ( Name, CategoryId ) VALUES  ( N‘猪肉‘, 2)
INSERT INTO dbo.Products ( Name, CategoryId ) VALUES  ( N‘牛肉‘, 2)
INSERT INTO dbo.Products ( Name, CategoryId ) VALUES  ( N‘人肉‘, 2)
GO
View Code

gxlsystem.com,布布扣

二、创建项目 WPFwithEFSample

gxlsystem.com,布布扣

三、更新 Entity Framework

gxlsystem.com,布布扣

gxlsystem.com,布布扣

四、创建Code First with Database

gxlsystem.com,布布扣

gxlsystem.com,布布扣

gxlsystem.com,布布扣

gxlsystem.com,布布扣

上面的步骤会自动生成实体类,所以需要编译一下,下一步的动作才会显示出需要的对象。

gxlsystem.com,布布扣

我们看下Code First with Database 工具帮我们生成了什么东东。

gxlsystem.com,布布扣

生成了3个文件,其中2个实体文件,分别对应数据库里的2张表Category 和 Product。还有一个MyShopContext.cs,这是数据库上下文,操作数据库的时候需要实例化此类。

gxlsystem.com,布布扣gxlsystem.com,布布扣
namespace WPFwithEFSample
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Category
    {
        public Category()
        {
            Products = new HashSet<Product>();
        }

        public int CategoryId { get; set; }

        public string Name { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }
}
Category.cs gxlsystem.com,布布扣gxlsystem.com,布布扣
namespace WPFwithEFSample
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Product
    {
        public int ProductId { get; set; }

        public string Name { get; set; }

        public int CategoryId { get; set; }

        public virtual Category Category { get; set; }
    }
}
Product.cs gxlsystem.com,布布扣gxlsystem.com,布布扣
namespace WPFwithEFSample
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class MyShopContext : DbContext
    {
        public MyShopContext()
            : base("name=MyShopContext")
        {
        }

        public virtual DbSet<Category> Categories { get; set; }
        public virtual DbSet<Product> Products { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }
}
MyShopContext.cs

MyShopContext.cs 代码中的 name=MyShopContext 值来自于配置文件 App.Config中的数据库连接字符串

gxlsystem.com,布布扣

  <connectionStrings>
    <add name="MyShopContext"
         connectionString="data source=.;initial catalog=MyShop;user id=sa;password=*******;MultipleActiveResultSets=True;App=EntityFramework"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

五、添加数据源,来自对象,也就是刚才用Code First with Database 工具生成的类,并且需要编译一次,否则向导工具发现不了!

     调出数据源窗口:视图  ->  其他窗口 ->  数据源   

     然后点击 数据库窗口的超链接“添加数据源...” 

gxlsystem.com,布布扣

gxlsystem.com,布布扣

如果没发现Category 和Product 选项,重新编译一下就可以了。

点击完成后,在数据源窗口会出现相关项:

gxlsystem.com,布布扣

生成的这些项后,我们就可以用鼠标拖到窗口后,就能创建界面控件

如果把Category用鼠标拖到界面就能创建GridView控件等

接下来我们就点击上面第一个Category项直接拖入到 MainWindow.xaml 图形界面,看看会产生什么。(不知道为什么每次都要拖2次才成功,可能是VS2013的bug吧)

gxlsystem.com,布布扣

拖入完后,会在2处自动添加代码,一个是 MainWindow.xaml , 另一个是 MainWindow.xaml.cs

gxlsystem.com,布布扣gxlsystem.com,布布扣
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:local="clr-namespace:WPFwithEFSample" mc:Ignorable="d" x:Class="WPFwithEFSample.MainWindow"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Window.Resources>
        <CollectionViewSource x:Key="categoryViewSource" d:DesignSource="{d:DesignInstance {x:Type local:Category}, CreateList=True}"/>
    </Window.Resources>
    <Grid DataContext="{StaticResource categoryViewSource}">

        <DataGrid x:Name="categoryDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="10,10,51,195" ItemsSource="{Binding}" EnableRowVirtualization="True" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="categoryIdColumn" Width="SizeToHeader" Header="Category Id" Binding="{Binding CategoryId}"/>
                <DataGridTextColumn x:Name="nameColumn" Width="SizeToHeader" Header="Name" Binding="{Binding Name}"/>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>
MainWindow.xaml gxlsystem.com,布布扣gxlsystem.com,布布扣
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFwithEFSample
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            System.Windows.Data.CollectionViewSource categoryViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource")));
            // 通过设置 CollectionViewSource.Source 属性加载数据: 
            // categoryViewSource.Source = [一般数据源]
        }
    }
}
MainWindow.xaml.cs

 接下来我们要分析一下这些自动生成的代码的用意。先看 MainWindow.xaml.cs,它就一条语句,意思是:在MainWindow.xaml 页面找到名为"categoryViewSource" 控件,并把他转换为CollectionViewSource类型。

private void Window_Loaded(object sender, RoutedEventArgs e)
{

    System.Windows.Data.CollectionViewSource categoryViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource")));
    // 通过设置 CollectionViewSource.Source 属性加载数据: 
    // categoryViewSource.Source = [一般数据源]
}

来看下 MainWindow.xaml
gxlsystem.com,布布扣

共自动生成了3大块代码,和其他的一些属性

 

明天继续。。。

WPF 数据绑定 使用Code First with Database,布布扣,bubuko.com

热门排行

今日推荐

热门手游