시퀸스 생성하는 프로시저 만들기

엔티티 모델에서 프로시저 등록하기

가져오기

        public int GetProgramSeq()
        {
            int i = 0;
            using (PbotEntities ctx = new PbotEntities())
            {
             
                var results = ctx.SP_GET_SEQ_PROGRAM();
                long? nextSequenceValue = results.SingleOrDefault();
             
                if( int.TryParse( nextSequenceValue.Value.ToString() , out i ))
                {
                    i = int.Parse(nextSequenceValue.Value.ToString());
                }

                return i;
            }
        }

 

Linq Distinct & Group by 하기

 

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();
또는
        var q = from c in dt.AsEnumerable()
                group c by c.Field<string>("WSOperate") into g
                select new
                {
                    WSOperate = g.Key
                };
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Orders orderList = new Orders();
            Order searchOrder = new Order(1, 1, "kojaedoo", 100, "kojaedoo", DateTime.Now);

           List<Order> list = orderList.ToList();

           var result = list.Where(delegate(Order a)
            {
                if (a.Name.Contains(searchOrder.Name))
                {
                    return true;
                }
                else
                {
                    return false;
                }

            });

        }

 

.

기존의 엔티티를 사용하면서 직접쿼리를 아래와 같이 할수있습니다.

엔티티로는 안되는  SEQUENCE 값이라든지(평션등을 이용하면 가능하지만 귀찮음) 

이런걸 사용 할 때  사용하면 좋을 꺼 같습니다.

Oracle

            OracleParameter op = new OracleParameter("NameVal", "kojaedoo");
            OracleParameter op2 = new OracleParameter("CompanyCodeVal", "0001");

            string query = @"INSERT INTO KOJAEDOO.PERSON (EMP_CODE, ""NAME"", COMPANY_CODE) VALUES(SEQUENCE1.NEXTVAL,:NameVal, :CompanyCodeVal )";
            db.ExecuteStoreCommand(query, op , op2);

MS Sql

예를 들어 다음의 두 메서드 호출은 동일합니다.

context.ExecuteStoreQuery<Product>("select * from Products where pid = {0}", 1);

context.ExecuteStoreQuery<Product>("select * from Products where pid = @p0", new SqlParameter { ParameterName = "p0", Value = 1 });
 
a

MSDN

using (SchoolEntities context =
    new SchoolEntities())
{
    // The following three queries demonstrate 
    // three different ways of passing a parameter.
    // The queries return a string result type.

    // Use the parameter substitution pattern.
    foreach (string name in context.ExecuteStoreQuery<string>
        ("Select Name from Department where DepartmentID < {0}", 5))
    {
        Console.WriteLine(name);
    }

    // Use parameter syntax with object values.
    foreach (string name in context.ExecuteStoreQuery<string>
        ("Select Name from Department where DepartmentID < @p0", 5))
    {
        Console.WriteLine(name);
    }
    // Use an explicit SqlParameter.
    foreach (string name in context.ExecuteStoreQuery<string>
        ("Select Name from Department where DepartmentID < @p0",
            new SqlParameter { ParameterName = "p0", Value = 5 }))
    {
        Console.WriteLine(name);
    }
}
msdn: http://msdn.microsoft.com/ko-kr/library/ee358769.aspx

데이터그리드에 바인딩되어져있는데이터를 검색 합니다.

image

 

image

CollectionViewSource에 데이터를 담아두고
ICollectionView _customerView = CollectionViewSource.GetDefaultView(__CollectionViewSource.View);
_customerView.Filter = CustomerFilter; 
필터 검색을 실행한다.
 

엔티티

image

데이터서비스

http://localhost:56323/WcfDataService1.svc

namespace WcfRestService1
{
    public class WcfDataService1 : DataService<NorthwindEntities>
    {


        public WcfDataService1()
        {

        }
       // 이 메서드는 서비스 전반적인 정책을 초기화하는 데 한 번만 호출됩니다.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: 규칙을 설정하여 어떤 엔터티 집합과 서비스 작업을 표시할 수 있고 업데이트할 수 있는지 등을 표시합니다.
            // 예제:
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

            //데이터베이스에서 자세한 오류가 반환되는지 여부
            config.UseVerboseErrors = true;

        }


    }
}

 

MainWindow.xaml

<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:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" xmlns:local="clr-namespace:테스트용" mc:Ignorable="d" x:Class="테스트용.MainWindow"
        Title="MainWindow" Height="350" Width="525" xmlns:my="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon">
    <Window.Resources>
 
    </Window.Resources>
    <Grid>
        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFA3A3A3" Offset="0.009"/>
                <GradientStop Color="#FF5E5E5E" Offset="0.997"/>
                <GradientStop Color="#FF2B2B2B" Offset="0.519"/>
            </LinearGradientBrush>
        </Grid.Background>
        
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <DataGrid Height="230" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479" />
        <Button Content="검색" Height="23" HorizontalAlignment="Left" Margin="416,248,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <TextBox Height="22" HorizontalAlignment="Left" Margin="290,249,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
        <Label Content="CompanyName" Margin="191.933,247,223,0" Name="label1" VerticalAlignment="Top" Foreground="White" d:LayoutOverrides="Width" />
    </Grid>
</Window>

 

MainWindow.xaml.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Reporting.WinForms;
using System.Net;
using System.IO;
using System.Data.Services.Client;
using System.ComponentModel;

namespace 테스트용
{
   
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {

        
       
        CollectionViewSource __CollectionViewSource = null;
        //엔티티 만들기
        ServiceReference1.NorthwindEntities __Context = new ServiceReference1.NorthwindEntities(new Uri("http://localhost:56323/WcfDataService1.svc"));
       
        public MainWindow()
        {
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);           
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //Customers 데이터를 CollectionViewSource 담아준다.
            //
            var query = from c in __Context.Customers
                        select c;

            __CollectionViewSource = new CollectionViewSource();
            __CollectionViewSource.Source = query.ToList();
            this.dataGrid1.ItemsSource = __CollectionViewSource.View;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView _customerView = CollectionViewSource.GetDefaultView(__CollectionViewSource.View);
            _customerView.Filter = CustomerFilter;
        }

        //검색 메소드
        private bool CustomerFilter(object item)
        {
            string searchKeyworld = this.textBox1.Text;
            ServiceReference1.Customers customer = item as ServiceReference1.Customers;
            
            return customer.CompanyName.Contains(searchKeyworld);

        }
    }
}

 

DataService<T>.OnStartProcessingRequest 메서드

각 요청을 처리하기 전에 호출됩니다. 일괄 요청의 경우 최상위 일괄 요청에 대해 한 번, 일괄 처리의 각 작업에 대해 한 번 호출됩니다.

네임스페이스: System.Data.Services
어셈블리: System.Data.Services(System.Data.Services.dll)

 

 

http://localhost:56323/WcfDataService1.svc/

image

우선프로그램 인증(로그인)을 받을떄

웹서비스 사이트에도 세션인증을 해줍니다.

그리고 OnStartProcessingRequest 이 일어날 때 세션체크 또는 폼 인증을 해주고 없으면 오류를 발생 시켜주면된다.

http://localhost:56323/WcfDataService1.svc/

image

image

C#.net 에서 Mysql 접속방법

다운로드 : http://dev.mysql.com/downloads/connector/net/
원문 : http://dev.mysql.com/doc/refman/5.1/en/connector-net-tutorials-entity-framework-winform-data-source.html
초간단 사용법 : http://dev.mysql.com/doc/refman/5.1/en/connector-net-tutorials-intro.html

더 간단하게 쓰라고
MySql.Data.MySqlClient 안에 MySqlHelper 가 들어가 있습니다.
간단한 사용법 http://www.dreamincode.net/forums/topic/199334-using-mysqlhelper/



여기서부터는 엔티티 만들어서 사용하는방법
20.2.4.5. Tutorial: Using an Entity Framework Entity as a Windows Forms Data Source

In this tutorial you will learn how to create a Windows Forms Data Source from an Entity in an Entity Data Model. This tutorial assumes that you have installed the World example database, which can be downloaded from the MySQL Documentation page. You can also find details on how to install the database on the same page. It will also be convenient for you to create a connection to the World database after it is installed. For instructions on how to do this see Section 20.2.3.1, “Making a connection”.

Creating a new Windows Forms application

The first step is to create a new Windows Forms application.

  1. In Visual Studio, select File, New, Project from the main menu.

  2. Choose the Windows Forms Application installed template. Click OK. The solution is created.

Adding an Entity Data Model

You will now add an Entity Data Model to your solution.

  1. In the Solution Explorer, right-click your application and select Add, New Item.... From Visual Studio installed templates select ADO.NET Entity Data Model. Click Add.

    Figure 20.38. Add Entity Data Model

    Add Entity Data Model
  2. You will now see the Entity Data Model Wizard. You will use the wizard to generate the Entity Data Model from the world example database. Select the icon Generate from database. Click Next.

    Figure 20.39. Entity Data Model Wizard Screen 1

    Entity Data Model Wizard Screen
              1
  3. You can now select the connection you made earlier to the World database. If you have not already done so, you can create the new connection at this time by clicking New Connection.... For further instructions on creating a connection to a database see Section 20.2.3.1, “Making a connection”.

    Figure 20.40. Entity Data Model Wizard Screen 2

    Entity Data Model Wizard Screen
              2
  4. Make a note of the entity connection settings to be used in App.Config, as these will be used later to write the necessary control code.

  5. Click Next.

  6. The Entity Data Model Wizard connects to the database. You are then presented with a tree structure of the database. From this you can select the object you would like to include in your model. If you had created Views and Stored Routines these will be displayed along with any tables. In this example you just need to select the tables. Click Finish to create the model and exit the wizard.

    Figure 20.41. Entity Data Model Wizard Screen 3

    Entity Data Model Wizard Screen
              3
  7. Visual Studio will generate the model and then display it.

    Figure 20.42. Entity Data Model Diagram

    Entity Data Model Diagram
  8. From the Visual Studio main menu select Build, Build Solution, to ensure that everything compiles correctly so far.

Adding a new Data Source

You will now add a new Data Source to your project and see how it can be used to read and write to the database.

  1. From the Visual Studio main menu select Data, Add New Data Source.... You will be presented with the Data Source Configuration Wizard.

    Figure 20.43. Entity Data Source Configuration Wizard Screen 1

    Entity Data Source Configuration Wizard
              Screen 1
  2. Select the Object icon. Click Next.

  3. You will now select the Object you wish to bind to. Expand the tree. In this tutorial you will select the city table. Once the city table has been selected click Next.

    Figure 20.44. Entity Data Source Configuration Wizard Screen 2

    Entity Data Source Configuration Wizard
              Screen 2
  4. The wizard will confirm that the city object is to be added. Click Finish.

    Figure 20.45. Entity Data Source Configuration Wizard Screen 3

    Entity Data Source Configuration Wizard
              Screen 3
  5. The city object will be display in the Data Sources panel. If the Data Sources panel is not displayed, select Data, Show Data Sources from the Visual Studio main menu. The docked panel will then be displayed.

    Figure 20.46. Data Sources

    Data Sources

Using the Data Source in a Windows Form

You will now learn how to use the Data Source in a Windows Form.

  1. In the Data Sources panel select the Data Source you just created and drag and drop it onto the Form Designer. By default the Data Source object will be added as a Data Grid View control. Note that the Data Grid View control is bound to the cityBindingSource and the Navigator control is bound to cityBindingNavigator.

    Figure 20.47. Data Form Designer

    Data Form Designer
  2. Save and rebuild the solution before continuing.

Adding Code to Populate the Data Grid View

You are now ready to add code to ensure that the Data Grid View control will be populated with data from the City database table.

  1. Double-click the form to access its code.

  2. Add code to instatiate the Entity Data Model's EntityContainer object and retrieve data from the database to populate the control.

    Figure 20.48. Adding Code to the Form

    Adding Code to the Form
  3. Save and rebuild the solution.

  4. Run the solution. Ensure the grid is populated and you can navigate the database.

    Figure 20.49. The Populated Grid Control

    The Populated Grid Control

Adding Code to Save Changes to the Database

You will now add code to enable you to save changes to the database.

The Binding source component ensures that changes made in the Data Grid View control are also made to the Entity classes bound to it. However, that data needs to be saved back from the entities to the database itself. This can be achieved by the enabling of the Save button in the Navigator control, and the addition of some code.

  1. In the Form Designer, click the Save icon in the Form toolbar and ensure that its Enabled property is set to True.

    Figure 20.50. Save Button Enabled

    Save Button Enabled
  2. Double-click the Save icon in the Form toolbar to display its code.

  3. You now need to add code to ensure that data is saved to the database when the save button is clicked in the application.

    Figure 20.51. Adding Save Code to the Form

    Adding Save Code to the Form
  4. Once the code has been added, save the solution and rebuild it. Run the application and verify that changes made in the grid are saved.

Linq Null Value SELECT

아래와 같이 ResourcesName 이라는 필드에 값이Null 일때 오류를 뱉어낸다

image

 

            var query = list.AsQueryable();
            var result = from c in query
                         where c.EngName.ToLower().Contains(this.txtSearchString.Text.ToLower()) || c.KorName.ToLower().Contains(this.txtSearchString.Text.ToLower())
                         || (c.ResourcesName == null ? "" : c.ResourcesName).Contains(this.txtSearchString.Text)
                         select c;

 

 

뭐 일단 이렇게 하니깐 잘되네??


DataSet ds = new DataSet();
FillOrders(ds); // this method fills the DataSet from a database

DataTable orders = ds.Tables["SalesOrderHeader"];

var query = from o in orders.ToQueryable()
            where o.Field<bool>("OnlineOrderFlag") == true
            select new { SalesOrderID = o.Field<int>("SalesOrderID"),
                         OrderDate = o.Field<DateTime>("OrderDate") };

foreach(var order in query) {
    Console.WriteLine("{0}\t{1:d}", order.SalesOrderID, order.OrderDate);
}

+ Recent posts