2016-09-29 10 views
2

Так что я пытаюсь получить мои «клиент» из моей базы данных, но я получаю исключениеДолжен объявить скалярную переменную @Id?

исключение типа «System.Data.SqlClient.SqlException» произошли в System.Data.dll но не обрабатывается в коде пользователя

Дополнительная информация: Должен объявить скалярную переменную "@Id".

using Core; 
    using System; 
    using System.Collections.Generic; 
    using System.Configuration; 
    using System.Data.SqlClient; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 

    namespace DatabaseAccess 
    { 
     public class DbCustomer 
     { 
      private string ConnectionString = ConfigurationManager.ConnectionStrings["local"].ConnectionString; 
      private SqlConnection connection { get; set; } 

      public DbCustomer() 
      { 
       connection = new SqlConnection(ConnectionString); 
      } 

      public Customer GetCustomer(int Id) 
      { 
       Customer customer = null; 
       connection.Open(); 

       using (SqlCommand command = connection.CreateCommand()) 
       { 
        command.CommandText = "SELECT * FROM CUSTOMER WHERE Id = @Id;"; 
        var reader = command.ExecuteReader(); 
        while (reader.Read()) 
        { 
         customer = new Customer(); 
         customer.Id = reader.GetInt32(reader.GetOrdinal("Id")); 
         customer.FirstName = reader.GetString(reader.GetOrdinal("FirstName")); 
         customer.LastName = reader.GetString(reader.GetOrdinal("LastName")); 
         customer.Address = reader.GetString(reader.GetOrdinal("Address")); 
        } 
        command.ExecuteNonQuery(); 
        connection.Close(); 
       } 
       return customer; 
      } 
     } 
    } 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Text; 
using System.Threading.Tasks; 

namespace Core 
{ 
    [DataContract] 
    public class Customer 
    { 
     [DataMember] 
     public int Id { get; set; } 
     [DataMember] 
     public string FirstName { get; set; } 
     [DataMember] 
     public string LastName { get; set; } 
     [DataMember] 
     public string Address { get; set; } 
     [DataMember] 
     public string Country { get; set; } 
     [DataMember] 
     public string PhoneNumber { get; set; } 

    } 
} 

using Core; 
using DatabaseAccess; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace BusinessLogic 
{ 
    public class CustomerController 
    { 
     public DbCustomer DbCustomer { get; set; } 

     public CustomerController() 
     { 
      DbCustomer = new DbCustomer(); 
     } 

     public Customer GetCustomer(int Id) 
     { 
      return DbCustomer.GetCustomer(Id); 
     } 
    } 
} 


using BusinessLogic; 
using Core; 
using DatabaseAccess; 
using System.Collections.Generic; 

namespace WCF 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together. 
    public class CustomerService : ICustomerService 
    { 
     CustomerController CustomerController = new CustomerController(); 

     public Customer GetCustomer(int Id) 
     { 
      return CustomerController.GetCustomer(Id); 
     } 

     public List<Customer> GetCustomers() 
     { 
      return new List<Customer>(); 
     } 
    } 
} 

using Core; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 

namespace WCF 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. 
    [ServiceContract] 
    public interface ICustomerService 
    { 
     [OperationContract] 
     Customer GetCustomer(int Id); 

     [OperationContract] 
     List<Customer> GetCustomers(); 

    } 
} 
+0

параметров нужно передать некоторые где право? –

+0

Вы устанавливаете параметр @id, но никогда не назначаете значение. Поэтому компилятор дает вам это исключение. – chris579

+3

Возможный дубликат ["Должен объявить скалярную переменную" ошибка] (http://stackoverflow.com/questions/21646877/must-declare-scalar-variable-error) –

ответ

4

Вы должны добавить SqlParameter с именем @Id

command.CommandText = "SELECT * FROM CUSTOMER WHERE Id = @Id;"; 
command.Parameters.Add("@Id", SqlDbType.Int32).Value = Id; 
6

Вы должны фактически передать в качестве параметра:

command.CommandText = "SELECT * FROM CUSTOMER WHERE Id = @Id;"; 
command.Parameters.Add("@Id", SqlDbType.Int).Value = Id; 
var reader = command.ExecuteReader(); 
+7

[Можно ли уже использовать AddWithValue() уже?] (Http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) –

+0

Странно наблюдать за этим конкретный пост, поднимающийся и опускаемый, проголосовал ... похоже, сфальсифицирован. – Kixoka

+0

@ScottChamberlain Скорректировано – Siyual

Смежные вопросы