Перевод specified cast is not valid

Как исправить ошибку «Specified cast is not valid» в C#?

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

Я сделал тип SQL int для IsAdmin , как меня просили, и в школе мне сказали, что int show bool в приложении, точнее, чтобы показать IsAdmin = True или False ?

Но когда я запускаю приложение и когда я прохожу экран входа в систему исключение отображается с сообщением:

Что мне нужно сделать?

Я пытался преобразовать этот (bool)reader[«IsAdmin»].ToInt32 , но он показывает ошибку.

Я попытался изменить его на целое число, но потом он показывает мне 1 и 0.

1 ответ

Я создаю GUI, и я использовал строку подключения для подключения базы данных сервера sql, позже я удалил предыдущую базу данных и построил новую с другим именем и изменил строку подключения в файле app.config. Но после этого он всегда показывал, что Specified cast is not valid и больше не может.

Этот SqlDataSource, который тянет из Oracle db, бросает Specified cast is not valid ONLY, когда я включаю c.item_cost в SQL. Если я удалю этот столбец, ошибки не будет. Это не имеет значения, если я действительно ссылаюсь на поле в коде.

Измените эту строку:

Преобразование необходимо, потому что вы не можете просто назначить int на bool . Я предполагаю, что в базе данных все, что больше 0 , означает, что пользователь является администратором.

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

  1. они занимают меньше места в базе данных (более эффективно)
  2. делает более очевидным , какова цель колонки
  3. устраняет проблемы с конвертацией , такие как размещенные в вопросе

Похожие вопросы:

У меня есть программа C#, которая должна извлекать данные из небольшой таблицы с четырьмя столбцами (.XLSX-файл). Он читает первый столбец нормально, однако, когда он доходит до второго, я получаю.

Я пытаюсь использовать SCOPE_IDENTITY, чтобы вернуть длинный первичный ключ обратно в c#, используя параметр ReturnValue для DynamicParameter. Вот пример кода с сайта Dapper: var p = new.

При запросе базы данных MS Access в веб-приложении API я получаю исключение Specified cast is not valid, если пытаюсь назначить пустую строку переменной. IOW, когда этот код: var accountID =.

Я создаю GUI, и я использовал строку подключения для подключения базы данных сервера sql, позже я удалил предыдущую базу данных и построил новую с другим именем и изменил строку подключения в файле.

Этот SqlDataSource, который тянет из Oracle db, бросает Specified cast is not valid ONLY, когда я включаю c.item_cost в SQL. Если я удалю этот столбец, ошибки не будет. Это не имеет значения, если я.

У меня есть забавная проблема. Я хочу выполнить этот запрос, но эта ошибка произойдет: Specified cast is not valid. Может ли кто-нибудь помочь мне? вот мой код: string connStr =.

Я использую свою программу для добавления учетных записей в базу данных. Я генерирую случайный номер счета, проверяю, существует ли этот номер счета в базе данных, и использую его для создания новой.

Почему это явное приведение создает исключение Specified cast is not valid. ? decimal d = 10m; object o = d; int x = (int)o; Но это работает: int x = (int)(decimal)o;

У меня есть следующие классы (я обрезал код): public class SqlWeightTrackerRepository : IWeightTrackerRepository < private Table m_weightTrackerTable; //. constructor + other.

Я использую следующий код для выполнения левого внешнего соединения между двумя таблицами; один из SQL и один из MySQL. В принципе, я хочу взять результирующий SQL datatable, добавить к нему.

Источник

Exception: Specified cast is not valid

When I put a breakpoint and debug the error comes from this line

I don’t understand why I get this error. Please help me!

EDIT: How can I convert (string)reader[«Role»] to UserRole??

6 Answers 6

Presumably UserRole is a type you have defined, hence the SqlDataReader does not know how to convert the data it gets from the database to this type. What is the type of this column in your database?

EDIT: As for your updated question you can do:

You might want to add in some extra error checking, eg checking that role is not null. Also, before parsing the enum you could check if the parse is valid using Enum.IsDefined.

(UserRole)reader[«Role»] should be (string)reader[«Role»] . There’s no UserRole type in SQL server.

The code is probably failing at:

because you’re trying to cast an object to a UserRole and the cast doesn’t exist.

It looks like you’re trying to cast reader[«Role»] to a UserRole Object and I’m guessing that’s what is failing.

You either need to specify (or implement) a valid cast, or implement something like UserRole.Parse(string value) to parse the string to a valid UserRole object.

If what you’re storing in the database is a string , but you want to convert it to an enum type, then you should use the Enum.Parse() method.

That means you either cannot cast (string)reader[«Username»] (not likely), or (UserRole)reader[«Role»] (more likely). What is UserRole — can you create it by casting from a db result? Don’t you need something like new UserRole(reader[«Role»]) ?

Probably (UserRole)Enum.Parse(typeof(UserRole), (string) reader[«Role»]) is the most appreciated answer, and furthermore, much to my surprise, it works!! (Surprising it is that the Enum.Parse method correctly converts even the string representation of the integers to its corresponding enum values, considering enum values in database is stored as integers). But this is what I often do, to be to the point:

This should be more efficient, though no way noticeable in real life.

Not the answer you’re looking for? Browse other questions tagged c# casting or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.11.6.37968

Источник

Specified cast is not valid on Includes #1748

Comments

Copy link Quote reply

0xdeafcafe commented Mar 4, 2015

When calling this code:

It throws the following error:
Additional Information: Specified cast is not valid

I checked the db, and the data is there and correct, so I don’t know what exactly could be causing this to throw. The stacktrace is below:

0xdeafcafe commented Mar 4, 2015

Should probably throw this in there too. I’m using 7.0.0-beta3

bradleylandis commented Mar 8, 2015

Did you make sure the types in your database match your model? Usually this comes from having something like int in your model and bigint in your database. In that case, changing your model to long fixes it.

In your case it would be on one of the included models. I’m especially suspicious of this since you refer to blobs and images. What type are you using in the database for those fields and what do your models look like?

A more specific error message would be nice here though.

maumar commented Mar 10, 2015

@0xdeafcafe Could you also share the model (and ideally some sample data) used to reproduce this? We fixed some issues around Include in the recent bits, some of them were around incorrect value readers being accessed for some entities (which could result in invalid casts, just like in your case).

Alternatively you could try one of our latest nightly builds to see if problem still exists.

0xdeafcafe commented Mar 10, 2015

I’m working on this project right now. I’ll try and repo this bug (I went though the models setting all Guid’s that hold Id’s to Nullables, so that might have fixed the casting error) when I finish something.

0xdeafcafe commented Mar 10, 2015

I changed all of the:

groups in my models to have Nullable Guid’s, then created and applied migrations. That seems to have fixed it.

maumar commented Mar 10, 2015

If possible, could you still share the original model? I case the original bug has not been fixed yet.

0xdeafcafe commented Mar 10, 2015

If I was wrong, and this is actually an issue with something else, I’ll update this post with the models as of the error, a copy of my db schema, and data to repo the issue.

maumar commented Mar 25, 2015

@0xdeafcafe I am unable to repro this in beta-3 or current bits, given the information you provided. Could you add some more info? (like you did in #1829). More specifically:

  • is dbset Trainers of type User or does it have it’s own type (if so, please provide)
  • entity that is part of TrainerBlobs navigation
  • DbContext (i.e. relevant mappings and dbset declarations)
  • data that was used to fill the database (TSQL format, similar to 1829 works fine)

maumar commented Jul 9, 2015

didn’t hear back, closing. Also we did some improvements around include, so the original issue may be already solved. Feel free to reopen if you still see the problem in the latest bits.

ndenkha commented Nov 30, 2016

Hi guys, I’m having this issue with EF 6.1.3 and it only happens when I include any 3rd Include, i.e. I can get a single or 2 navigation props in any combination fine. I’m running against MySQL 5.7 AWS RDS, and here are my models and tables.

// If I take any one of the includes I get the user object back correctly with only those two navigation props populated, the moment I add any 3rd include I get the error.

var existingUser =
Users.Include(x => x.Applications)
.Include(x => x.Roles)
.Include(x => x.Markets)
.FirstOrDefault(x => x.Id == user.Id);

public abstract class Trackable : ITrackable
<
public DateTime CreatedOn

public interface ITrackable
<
DateTime CreatedOn

public class Auditable : Trackable, IAuditable
<
public string CreatedBy

public interface IAuditable
<
string CreatedBy

public class AppUser : Auditable
<
public int Id

public class Application : Auditable
<
public int Id

public class Role : Auditable
<
public int Id

public class Market
<
public short Id

// Here are the mapping files.
public class ApplicationMap : EntityTypeConfiguration
<
public ApplicationMap()
<
ToTable(«Application»);

public class AppUserMap : EntityTypeConfiguration
<
public AppUserMap()
<
ToTable(«AppUser»);

public class RoleMap : EntityTypeConfiguration
<
public RoleMap()
<
ToTable(«Role»);

public class MarketMap : EntityTypeConfiguration
<
public MarketMap()
<
ToTable(«Market»);

public class ScopeMap : EntityTypeConfiguration
<
public ScopeMap()
<
ToTable(«Scope»);

// Here are the tables.

create table IF NOT EXISTS Application (
ApplicationId int not null auto_increment primary key,
Name varchar(255) not null,
IsDeleted bool not null default false,

create table IF NOT EXISTS AppUser (
UserId int not null auto_increment primary key,
Username varchar(255) not null,
FirstName varchar(255) not null,
LastName varchar(255) not null,
Email varchar(255) not null,
Title varchar(255) null,
IsActive bool not null default false,

create table IF NOT EXISTS Market (
EnterpriseMarketId smallint not null primary key,
Name varchar(255) not null,
State varchar(2) not null,
Region varchar(255) not null,
Timezone varchar(25) not null,
TimezoneOrder tinyint not null,
IsActive tinyint(1) not null
) ENGINE=INNODB;

create table IF NOT EXISTS Role (
RoleId int not null auto_increment primary key,
Name varchar(255) not null,
ApplicationId int not null,

create table IF NOT EXISTS Scope (
ScopeId int not null auto_increment primary key,
Name varchar(255) not null,
RoleId int not null,
Document JSON,

create table IF NOT EXISTS UserApplication (
ApplicationId int not null,
UserId int not null,

create table IF NOT EXISTS UserMarket (
EnterpriseMarketId smallint not null,
UserId int not null,

create table IF NOT EXISTS UserRole (
RoleId int not null,
UserId int not null,

Источник

Оцените статью
( Пока оценок нет )
Поделиться с друзьями
Uchenik.top - научные работы и подготовка
0 0 голоса
Article Rating
Подписаться
Уведомить о
guest
0 Комментарий
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии