ล็อกแล้ว filter Silverlight/WCF RIA Services

  • 6 มีนาคม 2555 21:50
     
      มีโค้ด

    hi i am new to sliver light and am have problems to filter by color heres the steps below i took let me know if i missed any  followed by the code 

    1 enable wcf ria services

    2 connect to DB

    3 add new item from data E D M

    4 add from web domain services class enable editing on table

    5 bulid ,  drag data grid from data sources , reset layout

    6 place data pager , drag data sources onto data pager change page size in prop's

    7 domain data source sort descriptors 

    8 domain data source prop's, filter descriptor , prop, path binding selectedvalue

    <UserControl x:Class="Adv_Tut.MainPage"
        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"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400"
                 xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices" 
                 xmlns:my="clr-namespace:Adv_Tut.Web"
                 xmlns:utils="clr-namespace:Adv_Tut.Utils"
                 xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
        <UserControl.Resources>
            <utils:ImageValueConverter x:Key="ImgValConv"/>
        </UserControl.Resources>
    
        <Grid x:Name="LayoutRoot" Background="White">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <riaControls:DomainDataSource AutoLoad="True" 
                                          d:DesignData="{d:DesignInstance my:Product, CreateList=true}" Height="0" 
                                          LoadedData="productDomainDataSource_LoadedData" 
                                          Name="productDomainDataSource" 
                                          QueryName="GetProductsQuery" Width="0">
                <riaControls:DomainDataSource.SortDescriptors>
                    <riaControls:SortDescriptor PropertyPath="Color" />
                </riaControls:DomainDataSource.SortDescriptors>
                <riaControls:DomainDataSource.GroupDescriptors>
                    <riaControls:GroupDescriptor PropertyPath="Color" />
                </riaControls:DomainDataSource.GroupDescriptors>
                <riaControls:DomainDataSource.FilterDescriptors>
                    <riaControls:FilterDescriptor Operator="IsGreaterThan" PropertyPath="Size" Value="50" />
                </riaControls:DomainDataSource.FilterDescriptors>
                <riaControls:DomainDataSource.DomainContext>
                    <my:DomainService1 />
                </riaControls:DomainDataSource.DomainContext>
            </riaControls:DomainDataSource>
            <sdk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ElementName=productDomainDataSource, Path=Data}" 
                          Name="productDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected">
                <sdk:DataGrid.Columns>
                    <sdk:DataGridTextColumn x:Name="colorColumn" Binding="{Binding Path=Color}" Header="Color" Width="SizeToHeader" />
                    <sdk:DataGridTemplateColumn x:Name="discontinuedDateColumn" Header="Discontinued Date" Width="SizeToHeader">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <sdk:DatePicker SelectedDate="{Binding Path=DiscontinuedDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true, TargetNullValue=''}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Path=DiscontinuedDate, StringFormat=\{0:d\}}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTextColumn x:Name="listPriceColumn" Binding="{Binding Path=ListPrice, StringFormat=\{0:c\}}" Header="List Price" Width="SizeToHeader" />
                    <sdk:DataGridTemplateColumn x:Name="modifiedDateColumn" Header="Modified Date" Width="SizeToHeader">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <sdk:DatePicker SelectedDate="{Binding Path=ModifiedDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Path=ModifiedDate, StringFormat=\{0:d\}}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Name}" Header="Name" Width="SizeToHeader" />
                    <sdk:DataGridTextColumn x:Name="productCategoryIDColumn" Binding="{Binding Path=ProductCategoryID}" Header="Product Category ID" Width="SizeToHeader" />
                    <sdk:DataGridTextColumn x:Name="productIDColumn" Binding="{Binding Path=ProductID, Mode=OneWay}" Header="Product ID" IsReadOnly="True" Width="SizeToHeader" />
                    <sdk:DataGridTextColumn x:Name="sizeColumn" Binding="{Binding Path=Size}" Header="Size" Width="SizeToHeader" />
                    <sdk:DataGridTextColumn x:Name="standardCostColumn" Binding="{Binding Path=StandardCost}" Header="Standard Cost" Width="SizeToHeader" />
                    <sdk:DataGridTextColumn x:Name="thumbnailPhoto1" Binding="{Binding Path=ThumbnailPhoto}" Header="Thumbnail" Width="SizeToHeader" />
                    <sdk:DataGridTemplateColumn x:Name="thumbnailPhoto" Header="Image" Width="SizeToHeader">
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="{Binding Path=ThumbNailPhoto, Converter={StaticResource ImgValConv}}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                </sdk:DataGrid.Columns>
            </sdk:DataGrid>
            
            <ListBox Grid.Row="1" ItemsSource="{Binding ElementName=productDomainDataSource, Path=Data}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontSize="16" Text="{Binding Path=Name}" Margin="0,0,5,0" FontStyle="Italic"></TextBlock>
                            <Image Source="{Binding Path=ThumbNailPhoto, Converter={StaticResource ImgValConv}}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </UserControl>

    .CS

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Adv_Tut.Web;
    using System.ServiceModel.DomainServices.Client;
    
    namespace Adv_Tut
    {
        public partial class MainPage : UserControl
        {
            DomainService1 dc = new DomainService1();
            public MainPage()
            {
                InitializeComponent();
            }
    
            private void productDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
            {
    
                if (e.HasError)
                {
                    System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                    e.MarkErrorAsHandled();
                }
            }
    
            private void UserControl_Loaded(object sender, RoutedEventArgs e)
            {
                productDomainDataSource.DataContext = dc;
                refreshColorDataGrid();
            }
    
            private void refreshColorDataGrid()
            {
                string selColor = txtSearchColor.Text;
                dc.Load(dc.GetProductByColorQuery(selColor), LoadOperation =>
                {
                    if (LoadOperation.HasError)
                    {
                        MessageBox.Show(LoadOperation.Error.Message);
                        LoadOperation.MarkErrorAsHandled();
                    }
                    this.productDataGrid.DataContext = LoadOperation.Entities;
                    dataPager1.DataContext = LoadOperation.Entities;
                }, null);
            }
    
    
            private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                //((Product)lbxProducts.SelectedItem).ProductID;
                //(int)lbxProducts.SelectedValue;
            }
    
            private void txtSearchColor_TextChanged(object sender, TextChangedEventArgs e)
            {
                dc.EntityContainer.GetEntitySet<Product>().Clear();
                refreshColorDataGrid();
            }
    
            private void productDomainDataSource1_LoadedData(object sender, LoadedDataEventArgs e)
            {
    
                if (e.HasError)
                {
                    System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                    e.MarkErrorAsHandled();
                }
            }
    
            private void btnsubmit_Click(object sender, RoutedEventArgs e)
            {
                dc.SubmitChanges();
    
                dc.SubmitChanges(delegate(SubmitOperation operation)
                {
                    if (operation.HasError)
                        MessageBox.Show(operation.Error.Message);
                    else
                        MessageBox.Show(operation.ChangeSet.First().ToString());
    
    
                }, null);
    
            }
        }   // end class
    }
    

    and domain services class

    namespace Adv_Tut.Web
    {
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using System.Data;
        using System.Linq;
        using System.ServiceModel.DomainServices.EntityFramework;
        using System.ServiceModel.DomainServices.Hosting;
        using System.ServiceModel.DomainServices.Server;
    
    
        // Implements application logic using the AdventureWorksLT2008R2Entities context.
        // TODO: Add your application logic to these methods or in additional methods.
        // TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
        // Also consider adding roles to restrict access as appropriate.
        // [RequiresAuthentication]
        [EnableClientAccess()]
        public class DomainService1 : LinqToEntitiesDomainService<AdventureWorksLT2008R2Entities>
        {
    
            // TODO:
            // Consider constraining the results of your query method.  If you need additional input you can
            // add parameters to this method or create additional query methods with different names.
            // To support paging you will need to add ordering to the 'Products' query.
            public IQueryable<Product> GetProducts()
            {
                return this.ObjectContext.Products;
                //var q = from p in ObjectContext.Products
                //        where p.ListPrice > 100
                //        orderby p.ListPrice descending
                //        select p;
                //return q;
    
            }
    
            public IQueryable<Product> GetProductByID(int pID)
            {
                var q = from p in ObjectContext.Products
                        where p.ProductID == pID
                        select p;
                return q;
            }
    
            public IQueryable<Product> GetProductByColor(string pColor)
            {
                IQueryable<Product> q = null ;
                if (string.IsNullOrEmpty(pColor)) q = from p in ObjectContext.Products select p;
                else{
                    q = from p in ObjectContext.Products
                        where p.Color == pColor
                        select p;}
                return q;
            }
    
            public void InsertProduct(Product product)
            {
                if ((product.EntityState != EntityState.Detached))
                {
                    this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Added);
                }
                else
                {
                    this.ObjectContext.Products.AddObject(product);
                }
            }
    
            public void UpdateProduct(Product currentProduct)
            {
                this.ObjectContext.Products.AttachAsModified(currentProduct, this.ChangeSet.GetOriginal(currentProduct));
            }
    
            public void DeleteProduct(Product product)
            {
                if ((product.EntityState != EntityState.Detached))
                {
                    this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Deleted);
                }
                else
                {
                    this.ObjectContext.Products.Attach(product);
                    this.ObjectContext.Products.DeleteObject(product);
                }
            }
    
            // TODO:
            // Consider constraining the results of your query method.  If you need additional input you can
            // add parameters to this method or create additional query methods with different names.
            // To support paging you will need to add ordering to the 'SalesOrderDetails' query.
            public IQueryable<SalesOrderDetail> GetSalesOrderDetails()
            {
                return this.ObjectContext.SalesOrderDetails;
            }
    
            // TODO:
            // Consider constraining the results of your query method.  If you need additional input you can
            // add parameters to this method or create additional query methods with different names.
            // To support paging you will need to add ordering to the 'SalesOrderHeaders' query.
            public IQueryable<SalesOrderHeader> GetSalesOrderHeaders()
            {
                return this.ObjectContext.SalesOrderHeaders;
            }
        }
    }
    
    


     

ตอบทั้งหมด

  • 12 มีนาคม 2555 10:38
     
      มีโค้ด

    i also tried to filter though the code with validation but to no avail below is my example.

                     

    <UserControl x:Class="Adv_Tut.MainPage" 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" mc:Ignorable="d" Loaded="UserControl_Loaded" xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices" xmlns:my="clr-namespace:Adv_Tut.Web" xmlns:utils="clr-namespace:Adv_Tut.Utils" xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"> <UserControl.Resources> <utils:ImageValueConverter x:Key="ImgValConv"/> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="Bisque"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <riaControls:DomainDataSource AutoLoad="True" LoadedData="productDomainDataSource_LoadedData" Name="productDomainDataSource" LoadSize="50"> <riaControls:DomainDataSource.SortDescriptors> <riaControls:SortDescriptor PropertyPath="Color" /> </riaControls:DomainDataSource.SortDescriptors> <!--<riaControls:DomainDataSource.GroupDescriptors> <riaControls:GroupDescriptor PropertyPath="Color" /> </riaControls:DomainDataSource.GroupDescriptors> <riaControls:DomainDataSource.FilterDescriptors> <riaControls:FilterDescriptor Operator="IsGreaterThan" PropertyPath="Size" Value="50" /> </riaControls:DomainDataSource.FilterDescriptors>--> </riaControls:DomainDataSource> <Border Padding="5"> <StackPanel> <sdk:Label FontSize="16" FontWeight="Bold" Foreground="DarkBlue">Choice of Color: </sdk:Label> <TextBox x:Name="txtSearchColor" TextChanged="txtSearchColor_TextChanged"></TextBox> </StackPanel> </Border> <Border Grid.Row="1" Padding="5"> <sdk:DataGrid AutoGenerateColumns="False" Margin="10" Name="productDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" ItemsSource="{Binding}"> <!--ItemsSource="{Binding ElementName=productDomainDataSource, Path=Data}"--> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn x:Name="colorColumn" Binding="{Binding Path=Color}" Header="Color" Width="SizeToHeader" /> <sdk:DataGridTemplateColumn x:Name="discontinuedDateColumn" Header="Discontinued Date" Width="SizeToHeader"> <sdk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <sdk:DatePicker SelectedDate="{Binding Path=DiscontinuedDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true, TargetNullValue=''}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellEditingTemplate> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=DiscontinuedDate, StringFormat=\{0:d\}}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTextColumn x:Name="listPriceColumn" Binding="{Binding Path=ListPrice, StringFormat=\{0:c\}}" Header="List Price" Width="SizeToHeader" /> <sdk:DataGridTemplateColumn x:Name="modifiedDateColumn" Header="Modified Date" Width="SizeToHeader"> <sdk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <sdk:DatePicker SelectedDate="{Binding Path=ModifiedDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellEditingTemplate> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=ModifiedDate, StringFormat=\{0:d\}}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Name}" Header="Name" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="productCategoryIDColumn" Binding="{Binding Path=ProductCategoryID}" Header="Product Category ID" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="productIDColumn" Binding="{Binding Path=ProductID, Mode=OneWay}" Header="Product ID" IsReadOnly="True" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="sizeColumn" Binding="{Binding Path=Size}" Header="Size" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="standardCostColumn" Binding="{Binding Path=StandardCost}" Header="Standard Cost" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="thumbnailPhoto1" Binding="{Binding Path=ThumbnailPhoto}" Header="Thumbnail" Width="SizeToHeader" /> <sdk:DataGridTemplateColumn x:Name="thumbnailPhoto" Header="Image" Width="SizeToHeader"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="{Binding Path=ThumbNailPhoto, Converter={StaticResource ImgValConv}}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> </Border> <StackPanel Grid.Row="2" Orientation="Horizontal"> <sdk:DataPager HorizontalAlignment="Center" Name="dataPager1" PageSize="15" Source="{Binding}" Margin="10,3"/> <Button x:Name="btnSubmit" Click="btnSubmit_Click">Submit</Button> </StackPanel> <Grid Grid.Row="3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <riaControls:DomainDataSource AutoLoad="True" d:DesignData="{d:DesignInstance my:Product, CreateList=true}" Height="0" LoadedData="productDomainDataSource_LoadedData" Name="productNameDomainDataSource" PageSize="15" LoadSize="50" QueryName="GetProductByID" Width="0"> <riaControls:DomainDataSource.QueryParameters> <riaControls:Parameter ParameterName="pID" Value="{Binding ElementName=lbxProducts, Path=SelectedValue}" /> </riaControls:DomainDataSource.QueryParameters> <riaControls:DomainDataSource.DomainContext> <my:DomainService1 /> </riaControls:DomainDataSource.DomainContext> </riaControls:DomainDataSource> <StackPanel Background="Beige" Grid.ColumnSpan="2"/> <riaControls:DomainDataSource AutoLoad="True" d:DesignData="{d:DesignInstance my:Product, CreateList=true}" Height="0" LoadedData="productDomainDataSource1_LoadedData" Name="productDomainDataSource1" QueryName="GetProductsQuery" Width="0"> <riaControls:DomainDataSource.DomainContext> <my:DomainService1 /> </riaControls:DomainDataSource.DomainContext> </riaControls:DomainDataSource> <ListBox SelectionChanged="ListBox_SelectionChanged" SelectedValuePath="ProductID" DisplayMemberPath="Name" Margin="5" x:Name="lbxProducts" ItemsSource="{Binding ElementName=productDomainDataSource1, Path=Data}"></ListBox> <StackPanel Grid.Column="1" DataContext="{Binding ElementName=productNameDomainDataSource, Path=Data}" Margin="5"> <TextBox FontSize="14" FontWeight="Bold" HorizontalAlignment="Center" Text="{Binding Name}"/> <Image Margin="0" Height="80" Width="80" Source="{Binding ThumbNailPhoto, Converter={StaticResource ImgValConv}}" HorizontalAlignment="Center" /> </StackPanel> </Grid> </Grid> </UserControl>

    and .cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Adv_Tut.Web;
    using System.ServiceModel.DomainServices.Client;
    
    namespace Adv_Tut
    {
        public partial class MainPage : UserControl
        {
            DomainService1 dc = new DomainService1();
            public MainPage()
            {
                InitializeComponent();
            }
    
            private void productDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
            {
    
                if (e.HasError)
                {
                    System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                    e.MarkErrorAsHandled();
                }
            }
    
            private void UserControl_Loaded(object sender, RoutedEventArgs e)
            {
                productDomainDataSource.DataContext = dc;
                // fill the data grid
                refreshColorDataGrid();
            }
    
            private void refreshColorDataGrid()
            {
                // select the colour from what the user entered
                string selColor = txtSearchColor.Text;
                // load the query 'GetProductByColor' and pass it the colour entered by the user
                dc.Load(dc.GetProductByColorQuery(selColor), LoadOperation =>
                {
                    if (LoadOperation.HasError)
                    {
                        MessageBox.Show(LoadOperation.Error.Message);
                        LoadOperation.MarkErrorAsHandled();
                    }
                    // if no error set the datagrid to show the entities of the query
                    this.productDataGrid.DataContext = LoadOperation.Entities;
                    // do the same for the data pager
                    dataPager1.DataContext = LoadOperation.Entities;
                }, null);
            }
    
    
            private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                //((Product)lbxProducts.SelectedItem).ProductID;
                //(int)lbxProducts.SelectedValue;
            }
    
            private void txtSearchColor_TextChanged(object sender, TextChangedEventArgs e)
            {
                dc.EntityContainer.GetEntitySet<Product>().Clear();
                refreshColorDataGrid();
            }
    
            private void productDomainDataSource1_LoadedData(object sender, LoadedDataEventArgs e)
            {
    
                if (e.HasError)
                {
                    System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                    e.MarkErrorAsHandled();
                }
            }
    
            private void btnSubmit_Click(object sender, RoutedEventArgs e)
            {
                //dc.SubmitChanges();   // Simple version
    
                dc.SubmitChanges(delegate(SubmitOperation operation)
                {
                    if (operation.HasError)
                        MessageBox.Show(operation.Error.Message);
                    else
                        MessageBox.Show(operation.ChangeSet.First().ToString());
                }, null);
            }
        }   // end class
    }
    

    domain service

    namespace Adv_Tut.Web
    {
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using System.Data;
        using System.Linq;
        using System.ServiceModel.DomainServices.EntityFramework;
        using System.ServiceModel.DomainServices.Hosting;
        using System.ServiceModel.DomainServices.Server;
    
    
        // Implements application logic using the AdventureWorksLT2008R2Entities context.
        // TODO: Add your application logic to these methods or in additional methods.
        // TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
        // Also consider adding roles to restrict access as appropriate.
        // [RequiresAuthentication]
        [EnableClientAccess()]
        public class DomainService1 : LinqToEntitiesDomainService<AdventureWorksLT2008R2Entities>
        {
    
            // TODO:
            // Consider constraining the results of your query method.  If you need additional input you can
            // add parameters to this method or create additional query methods with different names.
            // To support paging you will need to add ordering to the 'Products' query.
            public IQueryable<Product> GetProducts()
            {
                return this.ObjectContext.Products;
                //var q = from p in ObjectContext.Products
                //        where p.ListPrice > 100
                //        orderby p.ListPrice descending
                //        select p;
                //return q;
    
            }
    
            public IQueryable<Product> GetProductByID(int pID)
            {
                var q = from p in ObjectContext.Products
                        where p.ProductID == pID
                        select p;
                return q;
            }
    
            public IQueryable<Product> GetProductByColor(string pColor)
            {
                IQueryable<Product> q = null ;
                if (string.IsNullOrEmpty(pColor)) q = from p in ObjectContext.Products select p;
                else{
                    q = from p in ObjectContext.Products
                        where p.Color == pColor
                        select p;}
                return q;
            }
    
            public void InsertProduct(Product product)
            {
                if ((product.EntityState != EntityState.Detached))
                {
                    this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Added);
                }
                else
                {
                    this.ObjectContext.Products.AddObject(product);
                }
            }
    
            public void UpdateProduct(Product currentProduct)
            {
                this.ObjectContext.Products.AttachAsModified(currentProduct, this.ChangeSet.GetOriginal(currentProduct));
            }
    
            public void DeleteProduct(Product product)
            {
                if ((product.EntityState != EntityState.Detached))
                {
                    this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Deleted);
                }
                else
                {
                    this.ObjectContext.Products.Attach(product);
                    this.ObjectContext.Products.DeleteObject(product);
                }
            }
    
            // TODO:
            // Consider constraining the results of your query method.  If you need additional input you can
            // add parameters to this method or create additional query methods with different names.
            // To support paging you will need to add ordering to the 'SalesOrderDetails' query.
            public IQueryable<SalesOrderDetail> GetSalesOrderDetails()
            {
                return this.ObjectContext.SalesOrderDetails;
            }
    
            // TODO:
            // Consider constraining the results of your query method.  If you need additional input you can
            // add parameters to this method or create additional query methods with different names.
            // To support paging you will need to add ordering to the 'SalesOrderHeaders' query.
            public IQueryable<SalesOrderHeader> GetSalesOrderHeaders()
            {
                return this.ObjectContext.SalesOrderHeaders;
            }
        }
    }
    
    

    and Domain s metadata



    namespace Adv_Tut.Web
    {
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using System.Data.Objects.DataClasses;
        using System.Linq;
        using System.ServiceModel.DomainServices.Hosting;
        using System.ServiceModel.DomainServices.Server;




        // The MetadataTypeAttribute identifies ProductMetadata as the class
        // that carries additional metadata for the Product class.
        [MetadataTypeAttribute(typeof(Product.ProductMetadata))]
        public partial class Product
        {


            // This class allows you to attach custom attributes to properties
            // of the Product class.
            //
            // For example, the following marks the Xyz property as a
            // required property and specifies the format for valid values:
            //    [Required]
            //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
            //    [StringLength(32)]
            //    public string Xyz { get; set; }
            internal sealed class ProductMetadata
            {


                // Metadata classes are not meant to be instantiated.
                private ProductMetadata()
                {
                }


                public string Color { get; set; }


                public Nullable<DateTime> DiscontinuedDate { get; set; }


                public decimal ListPrice { get; set; }


                [CustomValidation(typeof(AdvRules),"IsModDateValid")]
                public DateTime ModifiedDate { get; set; }


                //[StringLength(20)]
                [Display(Name="Product Name")]
                public string Name { get; set; }


                public Nullable<int> ProductCategoryID { get; set; }


                public int ProductID { get; set; }


                public Nullable<int> ProductModelID { get; set; }


                public string ProductNumber { get; set; }


                public Guid rowguid { get; set; }


                public EntityCollection<SalesOrderDetail> SalesOrderDetails { get; set; }


                public Nullable<DateTime> SellEndDate { get; set; }


                public DateTime SellStartDate { get; set; }


                public string Size { get; set; }


                public decimal StandardCost { get; set; }


                public byte[] ThumbNailPhoto { get; set; }


                public string ThumbnailPhotoFileName { get; set; }


                public Nullable<decimal> Weight { get; set; }
            }
        }


        // The MetadataTypeAttribute identifies SalesOrderDetailMetadata as the class
        // that carries additional metadata for the SalesOrderDetail class.
        [MetadataTypeAttribute(typeof(SalesOrderDetail.SalesOrderDetailMetadata))]
        public partial class SalesOrderDetail
        {


            // This class allows you to attach custom attributes to properties
            // of the SalesOrderDetail class.
            //
            // For example, the following marks the Xyz property as a
            // required property and specifies the format for valid values:
            //    [Required]
            //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
            //    [StringLength(32)]
            //    public string Xyz { get; set; }
            internal sealed class SalesOrderDetailMetadata
            {


                // Metadata classes are not meant to be instantiated.
                private SalesOrderDetailMetadata()
                {
                }


                public decimal LineTotal { get; set; }


                public DateTime ModifiedDate { get; set; }


                public short OrderQty { get; set; }


                public Product Product { get; set; }


                public int ProductID { get; set; }


                public Guid rowguid { get; set; }


                public int SalesOrderDetailID { get; set; }


                public SalesOrderHeader SalesOrderHeader { get; set; }


                public int SalesOrderID { get; set; }


                public decimal UnitPrice { get; set; }


                public decimal UnitPriceDiscount { get; set; }
            }
        }


        // The MetadataTypeAttribute identifies SalesOrderHeaderMetadata as the class
        // that carries additional metadata for the SalesOrderHeader class.
        [MetadataTypeAttribute(typeof(SalesOrderHeader.SalesOrderHeaderMetadata))]
        public partial class SalesOrderHeader
        {


            // This class allows you to attach custom attributes to properties
            // of the SalesOrderHeader class.
            //
            // For example, the following marks the Xyz property as a
            // required property and specifies the format for valid values:
            //    [Required]
            //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
            //    [StringLength(32)]
            //    public string Xyz { get; set; }
            internal sealed class SalesOrderHeaderMetadata
            {


                // Metadata classes are not meant to be instantiated.
                private SalesOrderHeaderMetadata()
                {
                }


                public string AccountNumber { get; set; }


                public Nullable<int> BillToAddressID { get; set; }


                public string Comment { get; set; }


                public string CreditCardApprovalCode { get; set; }


                public int CustomerID { get; set; }


                public DateTime DueDate { get; set; }


                public decimal Freight { get; set; }


                public DateTime ModifiedDate { get; set; }


                public bool OnlineOrderFlag { get; set; }


                public DateTime OrderDate { get; set; }


                public string PurchaseOrderNumber { get; set; }


                public byte RevisionNumber { get; set; }


                public Guid rowguid { get; set; }


                public EntityCollection<SalesOrderDetail> SalesOrderDetails { get; set; }


                public int SalesOrderID { get; set; }


                public string SalesOrderNumber { get; set; }


                public Nullable<DateTime> ShipDate { get; set; }


                public string ShipMethod { get; set; }


                public Nullable<int> ShipToAddressID { get; set; }


                public byte Status { get; set; }


                public decimal SubTotal { get; set; }


                public decimal TaxAmt { get; set; }


                public decimal TotalDue { get; set; }
            }
        }
    }


  • 12 มีนาคม 2555 11:32
     
      มีโค้ด
    namespace Adv_Tut.Web
    {
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using System.Data.Objects.DataClasses;
        using System.Linq;
        using System.ServiceModel.DomainServices.Hosting;
        using System.ServiceModel.DomainServices.Server;
    
    
    
    
        // The MetadataTypeAttribute identifies ProductMetadata as the class
        // that carries additional metadata for the Product class.
        [MetadataTypeAttribute(typeof(Product.ProductMetadata))]
        public partial class Product
        {
    
    
            // This class allows you to attach custom attributes to properties
            // of the Product class.
            //
            // For example, the following marks the Xyz property as a
            // required property and specifies the format for valid values:
            //    [Required]
            //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
            //    [StringLength(32)]
            //    public string Xyz { get; set; }
            internal sealed class ProductMetadata
            {
    
    
                // Metadata classes are not meant to be instantiated.
                private ProductMetadata()
                {
                }
    
    
                public string Color { get; set; }
    
    
                public Nullable<DateTime> DiscontinuedDate { get; set; }
    
    
                public decimal ListPrice { get; set; }
    
    
                [CustomValidation(typeof(AdvRules),"IsModDateValid")]
                public DateTime ModifiedDate { get; set; }
    
    
                //[StringLength(20)]
                [Display(Name="Product Name")]
                public string Name { get; set; }
    
    
                public Nullable<int> ProductCategoryID { get; set; }
    
    
                public int ProductID { get; set; }
    
    
                public Nullable<int> ProductModelID { get; set; }
    
    
                public string ProductNumber { get; set; }
    
    
                public Guid rowguid { get; set; }
    
    
                public EntityCollection<SalesOrderDetail> SalesOrderDetails { get; set; }
    
    
                public Nullable<DateTime> SellEndDate { get; set; }
    
    
                public DateTime SellStartDate { get; set; }
    
    
                public string Size { get; set; }
    
    
                public decimal StandardCost { get; set; }
    
    
                public byte[] ThumbNailPhoto { get; set; }
    
    
                public string ThumbnailPhotoFileName { get; set; }
    
    
                public Nullable<decimal> Weight { get; set; }
            }
        }
    
    
        // The MetadataTypeAttribute identifies SalesOrderDetailMetadata as the class
        // that carries additional metadata for the SalesOrderDetail class.
        [MetadataTypeAttribute(typeof(SalesOrderDetail.SalesOrderDetailMetadata))]
        public partial class SalesOrderDetail
        {
    
    
            // This class allows you to attach custom attributes to properties
            // of the SalesOrderDetail class.
            //
            // For example, the following marks the Xyz property as a
            // required property and specifies the format for valid values:
            //    [Required]
            //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
            //    [StringLength(32)]
            //    public string Xyz { get; set; }
            internal sealed class SalesOrderDetailMetadata
            {
    
    
                // Metadata classes are not meant to be instantiated.
                private SalesOrderDetailMetadata()
                {
                }
    
    
                public decimal LineTotal { get; set; }
    
    
                public DateTime ModifiedDate { get; set; }
    
    
                public short OrderQty { get; set; }
    
    
                public Product Product { get; set; }
    
    
                public int ProductID { get; set; }
    
    
                public Guid rowguid { get; set; }
    
    
                public int SalesOrderDetailID { get; set; }
    
    
                public SalesOrderHeader SalesOrderHeader { get; set; }
    
    
                public int SalesOrderID { get; set; }
    
    
                public decimal UnitPrice { get; set; }
    
    
                public decimal UnitPriceDiscount { get; set; }
            }
        }
    
    
        // The MetadataTypeAttribute identifies SalesOrderHeaderMetadata as the class
        // that carries additional metadata for the SalesOrderHeader class.
        [MetadataTypeAttribute(typeof(SalesOrderHeader.SalesOrderHeaderMetadata))]
        public partial class SalesOrderHeader
        {
    
    
            // This class allows you to attach custom attributes to properties
            // of the SalesOrderHeader class.
            //
            // For example, the following marks the Xyz property as a
            // required property and specifies the format for valid values:
            //    [Required]
            //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
            //    [StringLength(32)]
            //    public string Xyz { get; set; }
            internal sealed class SalesOrderHeaderMetadata
            {
    
    
                // Metadata classes are not meant to be instantiated.
                private SalesOrderHeaderMetadata()
                {
                }
    
    
                public string AccountNumber { get; set; }
    
    
                public Nullable<int> BillToAddressID { get; set; }
    
    
                public string Comment { get; set; }
    
    
                public string CreditCardApprovalCode { get; set; }
    
    
                public int CustomerID { get; set; }
    
    
                public DateTime DueDate { get; set; }
    
    
                public decimal Freight { get; set; }
    
    
                public DateTime ModifiedDate { get; set; }
    
    
                public bool OnlineOrderFlag { get; set; }
    
    
                public DateTime OrderDate { get; set; }
    
    
                public string PurchaseOrderNumber { get; set; }
    
    
                public byte RevisionNumber { get; set; }
    
    
                public Guid rowguid { get; set; }
    
    
                public EntityCollection<SalesOrderDetail> SalesOrderDetails { get; set; }
    
    
                public int SalesOrderID { get; set; }
    
    
                public string SalesOrderNumber { get; set; }
    
    
                public Nullable<DateTime> ShipDate { get; set; }
    
    
                public string ShipMethod { get; set; }
    
    
                public Nullable<int> ShipToAddressID { get; set; }
    
    
                public byte Status { get; set; }
    
    
                public decimal SubTotal { get; set; }
    
    
                public decimal TaxAmt { get; set; }
    
    
                public decimal TotalDue { get; set; }
            }
        }
    }