Data conversion error converting enum

I'm using Entity Framework Core 3.1 and trying to do a simple query on an enum property in my entity in my localdb and I keep getting this error: Enum conversion failed when converting the nvarc...

I’m using Entity Framework Core 3.1 and trying to do a simple query on an enum property in my entity in my localdb and I keep getting this error:

Enum conversion failed when converting the nvarchar value ‘Accountant’ to data type int

Entity:

public class DemoEntity
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Position Position { get; set; }
}

Enum — Position:

public enum Position
{
    [Display(Name = "Accountant")]
    Accountant,
    [Display(Name = "Chief Executive Officer (CEO)")]
    ChiefExecutiveOfficer,
    [Display(Name = "Integration Specialist")]
    IntegrationSpecialist,
    [Display(Name = "Junior Technical Author")]
    JuniorTechnicalAuthor,
    [Display(Name = "Pre Sales Support")]
    PreSalesSupport,
    [Display(Name = "Sales Assistant")]
    SalesAssistant,
    [Display(Name = "Senior Javascript Developer")]
    SeniorJavascriptDeveloper,
    [Display(Name = "Software Engineer")]
    SoftwareEngineer
}

DbContext:

public class DemoDbContext : DbContext
{
    public DemoDbContext(DbContextOptions options)
        : base(options) { }

    public DbSet<DemoEntity> Demos { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //var converter = new ValueConverter<Position, string>(
        //                    v => v.ToString(),
        //                    v => (Position)Enum.Parse(typeof(Position), v));

        //var converter = new EnumToStringConverter<Position>();

        modelBuilder
            .Entity<DemoEntity>()
            .Property(e => e.Position);
            //.HasColumnType("nvarchar(max)")
            //.HasConversion<string>();
            //.HasConversion(converter);
    }
}

I tried adding value conversions:

  1. .HasConversion<string>() — didn’t work
  2. .HasConversion(converter) — didn’t work

When I query the table as follows I’m getting the conversion error

try
{
    var test = await query.Where(x => x.Position.Equals(Position.Accountant)).ToListAsync();
}
catch (System.Exception e)
{
    //throw;
}

The Position is of type NVARCHAR(MAX) in my database.

enter image description here

enter image description here

Am I missing anything simple? Not able to figure where I’m going wrong. Please assist.

@fingers10 Thanks!

@smitpatel Enum mapped to a string column. This works:

var test = context
    .Set<DemoEntity>()
    .Where(x => x.Position == Position.Accountant)
    .ToList();

This throws:

var test = context
    .Set<DemoEntity>()
    .Where(x => x.Position.Equals(Position.Accountant))
    .ToList();
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT [d].[Id], [d].[FirstName], [d].[LastName], [d].[Position]
      FROM [DemoEntity] AS [d]
      WHERE [d].[Position] = 0
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'SomeDbContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'IntegrationSpecialist' to data type int.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
         at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
         at Microsoft.Data.SqlClient.SqlDataReader.Read()
         at Microsoft.EntityFrameworkCore.Storage.RelationalDataReader.Read()
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
      ClientConnectionId:8005ae9a-5c3c-4779-95d4-eb879babd01c
      Error Number:245,State:1,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'IntegrationSpecialist' to data type int.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
   at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
   at Microsoft.Data.SqlClient.SqlDataReader.Read()
   at Microsoft.EntityFrameworkCore.Storage.RelationalDataReader.Read()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:8005ae9a-5c3c-4779-95d4-eb879babd01c
Error Number:245,State:1,Class:16
Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'IntegrationSpecialist' to data type int.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
   at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
   at Microsoft.Data.SqlClient.SqlDataReader.Read()
   at Microsoft.EntityFrameworkCore.Storage.RelationalDataReader.Read()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Program.Main() in /home/ajcvickers/AllTogetherNow/Daily/Daily.cs:line 61
ClientConnectionId:8005ae9a-5c3c-4779-95d4-eb879babd01c
Error Number:245,State:1,Class:16

У меня проблема с помещением аргументов метода в мой класс:

class A {
  public:
    enum Mode {ModeA, ModeB, ModeC};

    ... // other methods, constructor etc

    void setMode(Mode m) {
      mMode = m;
    }

  private:
    Mode mMode;
}

int main(int argc, char **argv) {
  A a;
  a.setMode(A::ModeA | A::ModeC );

  return 0;
}

Проблема, я получаю ошибку компилятора C++ invalid vconversion from int to A::Mode, я не понимаю, почему я не могу объединить значения перечисления? Мне нужно объединить значения в моем коде, поэтому любая помощь в решении этой проблемы была бы очень хорошей.

3 ответы

Результат operator| для двух перечислений не является перечислением по умолчанию. После вашего класса добавьте что-то вроде этого:

A::Mode operator|( A::Mode a, A::Mode b )
{
    return A::Mode( int( a ) | int( b ) );
}

если ваша стандартная библиотека поддерживает это, следующее больше подходит для будущего, поскольку преобразование в int не всегда правильно:

A::Mode operator|( A::Mode a, A::Mode b )
{
    typedef std::underlying_type< A::Mode >::type UL;
    return A::Mode( static_cast< UL >( a ) | static_cast< UL >( b ) );
}

В отличие от другого ответа, вы просто добавляете это один раз (в нужное место), и все виды использования автоматически охватываются.

ответ дан 12 окт ’13, 18:10

Может быть, вам это нужно:

a.setMode( (A::Mode) (A::ModeA | A::ModeC ));

A::ModeA | A::ModeC Делает int так бросьте это на A::Mode снова

ответ дан 12 окт ’13, 18:10

Основной тип вашего enum в этом случае наверное int и ваш компилятор не может полагаться на флаг, построенный с использованием | (побитовое или) является допустимым значением из этого перечисления.

Однако вы знаете, что результатом будет допустимое значение из этого перечисления, поэтому вы можете сделать:

A::Mode newMode = (A::Mode) (A::ModeA | A::ModeC);
a.setMode(newMode);

ответ дан 12 окт ’13, 18:10

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c++
enums

or задайте свой вопрос.

#include <stdio.h>
typedef enum{
red=1,blue,green
}color;

void set_color(color *c)
{
  *c = blue;
}

int main()
{
  //int a = 3;
  //set_color(&a);//why this error?
  //set_color((color *)(&a));//It is right
  color c = red;
  set_color(&c); // this is right;
  return 0;
}

i use gcc -S to view the assemble language with set_color((color *)(&a)) and it is the same with set_color(&c),but why gcc does not do the convertion automatically?


Solution 1

Solution 2

Because it is trying to prevent you making a mistake, and you not realizing it.
When you write

set_color((color *)(&a));

You are explicitly converting it — telling the compiler «this is the value I wanted to send, I know what I am doing» so it lets it through.

When you write

set_color(&a);

It could be a mistake — you might not have realised that «a» was not a color at all. So it raises an error so you can fix the problem before it becomes a run time problem and causes an odd bug.

Comments

In gcc, the int and the emun are allocated the same memory size 4 bytes, so it should be safe.

Doesn’t matter — it will be safe because all enums (unless sepcifically stated otherwise) are based on an integer. The compiler is telling you that this could be an unsafe operation from a program logic point of view, rather than from a execution run-time-error point of view.

Thank you for your explanation. I have underundered the problem.You are right , from the view of compiler i should consider the program logic.

Solution 3

In C (and C++), the datatypes ‘int’ and ‘enum’ are partly typesafe. For example:

typedef enum {E0 = 0, E1 = 1} ENUMtype_t;

ENUMtype_t e = E0;  // legal
int i = 0;          // legal
i = E0;             // legal
e = 0;              // legal(!)
e = 1;              // error(!)
e = i;              // error
e = (ENUMtype_t) i; // legal
  • Remove From My Forums
  • Question

  • How to cast an instance of the Enum class to an int?

    I can cast an Enum to an object. And then cast that object to int. But the compiler errors when I cast the Enum directly to an int. Why would that be?

      public enum Furniture
      {
        none = 0,
        chair,
        table,
        stool
      }
    
        private void EnumTester( )
        {
          Furniture furniture = Furniture.stool;
          EnumObjectTester(furniture);
        }
    
        private void EnumObjectTester( Enum enumValue )
        {
          Debug.Print(enumValue.GetType().ToString());
          Debug.Print(enumValue.ToString());
    
          // this works. Can cast an Enum to an object. And then cast the object to int.
          object enumObject = enumValue;
          int intValue = (int)enumObject;
    
          // but casting the Enum object directly to int does not work.
          // error is: Error CS0030  Cannot convert type 'System.Enum' to 'int'  
          intValue = (int)enumValue;
          Debug.Print("intValue:" + intValue);
        }
    

Answers

  • This is the CLR rules, if you are casting to a destination type the source type should be allowed to be casted as per the pre-defined rules, if not you will receive the above error. This is not the case when casting float to int or else, because this is
    allowed.

    However, you can do what you looking for via conversion (which normally returns an error on runtime if both values are incompatible for conversion):

     Enum enumFurniture = furniture;
     int enumInt = Convert.ToInt32(enumFurniture);

    Its a lengthy subject that I suggest to do some research for more info:

    https://msdn.microsoft.com/en-us/library/98bbex99(v=vs.110).aspx#Convert

    https://msdn.microsoft.com/en-us/library/ms173105.aspx


    Fouad Roumieh

    • Proposed as answer by

      Thursday, June 2, 2016 2:39 PM

    • Marked as answer by
      Steve Richter
      Thursday, June 2, 2016 5:25 PM

Hi,

I am transferring data from a Flat file source to SQL Database. Initially I got validation error saying

«Validation error. Import Employee Information: [DataFlowTask] [6384]: The column «[ColumnName] » can’t be inserted because the conversion between types DT_STR and DT_DBTIMESTAMP is not supported.» ( i have 6 date fields)

The destination in SQL has the field in «datetime» format.

So i used a «Data Conversion» task to transform the fields, thereby resolving the validation errors. But when i Execute the dtsx I get the following error :

[Data Conversion [322]] Error: Data conversion failed while converting column «[ColumnName]» (79) to column «[Modified_ColumnName]» (346).  The conversion returned status value 2 and status text «The value could not be converted because of a potential loss of data.».

[Data Conversion [322]] Error: The «output column «[Modified_ColumnName]» (346)» failed because error code 0xC020907F occurred, and the error row disposition on «output column «[Modified_ColumnName]» (346)» specifies failure on error. An error occurred on the specified object of the specified component.

[DTS.Pipeline] Error: The ProcessInput method on component «Data Conversion» (322) failed with error code 0xC0209029. The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.

[DTS.Pipeline] Error: Thread «WorkThread0» has exited with error code 0xC0209029.

[«InputFileName» Input [1]] Error: Setting the end of rowset for the buffer failed with error code 0xC0047020.

[DTS.Pipeline] Error: The PrimeOutput method on component «InputFileName Input» (1) returned error code 0xC0209017.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.

[DTS.Pipeline] Error: Thread «SourceThread0» has exited with error code 0xC0047038.

Can anybody help me with this?

vladuhus

0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

1

02.12.2019, 08:08. Показов 8787. Ответов 13

Метки нет (Все метки)


Пытаюсь подсчитать кол-во записей в таблице которые имеют введенный Логин, но встречаю эту ошибку:
System.Data.SqlClient.SqlException: «Conversion failed when converting the nvarchar value ‘dsfdsaf’ to data type int.»,
где dsfdsaf — логин пользователя.
Ошибка появляется здесь:

VB.NET
1
2
SqlCommand UsersCount = new SqlCommand("SELECT COUNT(*) FROM [Clients] WHERE [login] = " + TextBox1.Text, sqlConnection);
                    int count = Convert.ToInt32(UsersCount.ExecuteScalar());

Подскажите, почему так происходит и как это исправить?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

02.12.2019, 12:45

2

vladuhus, нужен полный текст ошибки , включая данные из stacktrace.
+ скрин части кода с местом ошибки
+ скрин схемы БД

П.С В запросе , значение TextBox1.Text нужно обернуть в кавычки , если login сравнивается со строкой.
+ параметры запроса лучше подставлять через SqlParams , иначе есть риск sql иньекций.



1



vladuhus

0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

02.12.2019, 14:15

 [ТС]

3

Код с ошибкой:

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class LoginSite : System.Web.UI.Page
    {
        public int idcookie;
        public string rules;
            private SqlConnection sqlConnection = null;
        protected async void Page_Load(object sender, EventArgs e)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            sqlConnection = new SqlConnection(connectionString);
            await sqlConnection.OpenAsync();
        }
 
        protected async void Button1_Click(object sender, EventArgs e)
        {
 
            Dictionary<string, string> db = new Dictionary<string, string>();
            SqlCommand getUsersCredCmd = new SqlCommand("SELECT [login], [password] FROM [Users]", sqlConnection);
            SqlDataReader sqlReader = null;
            try
            {
                sqlReader = await getUsersCredCmd.ExecuteReaderAsync();
                while (await sqlReader.ReadAsync())
                {
                    db.Add(Convert.ToString(sqlReader["login"]), Convert.ToString(sqlReader["password"]));
                }
            }
            catch { }
            finally
            {
                if (sqlReader != null)
                    sqlReader.Close();
            }
           // try
            {
                if (TextBox2.Text == db[TextBox1.Text])
                {
                    SqlCommand UsersCount = new SqlCommand("SELECT COUNT(*) FROM [Clients] WHERE [login] = " + TextBox1.Text, sqlConnection);
                    int count = Convert.ToInt32(UsersCount.ExecuteScalar());
                    if (count > 0)
                    {
                        SqlCommand UserID = new SqlCommand("SELECT [id] FROM [Clients] WHERE [login] = " + TextBox1.Text, sqlConnection);
                        int userid = Convert.ToInt32(UserID.ExecuteScalar());
                        idcookie = userid;
                        rules = "Client";
                    }
                    else
                    {
                        SqlCommand UserID = new SqlCommand("SELECT [id] FROM [Drivers] WHERE [login] = " + TextBox1.Text, sqlConnection);
                        int userid = Convert.ToInt32(UserID.ExecuteScalar());
                        idcookie = userid;
                        rules = "Driver";
                    }
                    HttpCookie rulecookie = new HttpCookie("rules", rules);
                    HttpCookie id = new HttpCookie("id", idcookie.ToString());
                    HttpCookie login = new HttpCookie("login", TextBox1.Text);
                    HttpCookie sign = new HttpCookie("sign", SignGenerator.GetSign(TextBox2.Text + "bytepp"));
                    HttpCookie signrule = new HttpCookie("signrule", SignGenerator.GetSign(rules + "bytepp"));
                    Response.Cookies.Add(login);
                    Response.Cookies.Add(sign);
                    Response.Redirect("WelcomeSite.aspx", false);
                }
                else
                {
                    string script = "alert('Неверный логин или пароль');";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "MessageBox", script, true);
                }
            }
           // catch
            {
 
               //string script = "alert('Введите логин и пароль');";
                //ClientScript.RegisterClientScriptBlock(this.GetType(), "MessageBox", script, true);
 
            }
 
        }
    }
 }

Миниатюры

Conversion failed when converting the nvarchar value to data type int при подсчете записей
 

Conversion failed when converting the nvarchar value to data type int при подсчете записей
 



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

02.12.2019, 16:08

4

vladuhus, хм , откройте как вкладочку «Триггеры» — скорее всего , есть триггер на таблице клиентов.
— ошибка должна быть вида «Недопустимое имя столбца» т.к Вы неправильно запрос строите , но вместо этого , у Вас на уровне БД ошибка конвертации , притом, что в самом запросе никакой конвертации не видно.



0



0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

03.12.2019, 06:34

 [ТС]

5

sau, Нет, триггеров я не создавал, папка абсолютно пустая.



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

03.12.2019, 09:28

6

vladuhus, проверьте , работает ли какой либо запрос к таблице Clients



0



vladuhus

0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

03.12.2019, 11:57

 [ТС]

7

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
SqlCommand reguser = new SqlCommand("INSERT INTO [Users] (login, password)VALUES(@login, @password)", sqlConnection);
                reguser.Parameters.AddWithValue("login", TextBox1.Text);
                reguser.Parameters.AddWithValue("password", TextBox2.Text);
                await reguser.ExecuteNonQueryAsync();
                //SqlCommand UserID = new SqlCommand("SELECT [id] FROM [Users] WHERE [login] = " + TextBox1.Text, sqlConnection);
                //SqlDataReader sqlReaderID = null;
                //sqlReaderID = await UserID.ExecuteReaderAsync();
                //int userid = Convert.ToInt32(UserID.ExecuteScalar());
                reguser = new SqlCommand("INSERT INTO [Clients] (name, surname, fathername, phone, login)VALUES(@name, @surname,@fathername,@phone, @login)", sqlConnection);
                reguser.Parameters.AddWithValue("name", TextBox3.Text);
                reguser.Parameters.AddWithValue("surname", TextBox4.Text);
                reguser.Parameters.AddWithValue("fathername", TextBox5.Text);
                reguser.Parameters.AddWithValue("phone", TextBox6.Text);
                reguser.Parameters.AddWithValue("login", TextBox1.Text);
                Response.Redirect("LoginSite.aspx", false);
                await reguser.ExecuteNonQueryAsync();

Запрос на добавление работает. Здесь же не работает выборка id из Users, с той же ошибкой



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

03.12.2019, 14:13

8

vladuhus,
покажите содержимое папки Триггеры



1



0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

04.12.2019, 01:18

 [ТС]

9

Вот, пусто

Миниатюры

Conversion failed when converting the nvarchar value to data type int при подсчете записей
 



0



kolorotur

Эксперт .NET

16930 / 12507 / 3286

Регистрация: 17.09.2011

Сообщений: 20,743

04.12.2019, 02:49

10

Цитата
Сообщение от vladuhus
Посмотреть сообщение

Запрос на добавление работает.

А по какой причине вы не пользуетесь параметризованным запросом при подсчете элементов?
У вас, например, из-за этого строковое значение не в кавычках и запрос выглядит так:

SQL
1
SELECT COUNT(*) FROM [Clients] WHERE [login] = dsfdsaf

Вместо такого:

SQL
1
SELECT COUNT(*) FROM [Clients] WHERE [login] = 'dsfdsaf'

Причина, может, и не в этом, но начните с правильного построения запроса — с использованием параметров.



1



vladuhus

0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

04.12.2019, 11:47

 [ТС]

11

VB.NET
1
SqlCommand UsersCount = new SqlCommand("SELECT COUNT(*) FROM [Clients] WHERE [login] = '" + TextBox1.Text+"'", sqlConnection);

Написал запрос таким образом вроде начал работать. Посмотрим, что будет дальше



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

04.12.2019, 11:56

12

vladuhus, странное описание ошибки , причем тут converting to data type int ?…
— обычно , на запрос вида SELECT COUNT(*) FROM [Clients] WHERE [login] = dsfdsaf , должен ругнуться на недопустимое имя столбца. А какой версии сервер БД ?
— может на уровне обьектов сервера есть какой перехват exeption, который пытается обработать некорректный select и валится на преобразовании.



0



0 / 0 / 0

Регистрация: 20.04.2018

Сообщений: 10

04.12.2019, 11:58

 [ТС]

13

SQL Server 2014
P.S.
Как делать упоминание пользователя на этом форуме?



0



Эксперт .NET

16930 / 12507 / 3286

Регистрация: 17.09.2011

Сообщений: 20,743

04.12.2019, 15:32

14

Цитата
Сообщение от vladuhus
Посмотреть сообщение

Написал запрос таким образом

Напишите в TextBox1 такую строку:

Код

' OR 1 = 1; DROP TABLE [Clients]; --

И поймите уже, почему всегда нужно использовать параметризованные запросы, если значения параметров приходят извне, т.е. находятся вне вашего контроля.



0



Понравилась статья? Поделить с друзьями:
  • Data address mark error
  • Dashchan ошибка расширения
  • Dashchan ошибка при загрузке данных
  • Dash 3 media err decode ошибка
  • Dash 27 https ошибка