The exception that is thrown when server-related issues occur.
Inheritance
NpgsqlException
Implements
Inherited Members
Namespace: Npgsql
Assembly: Npgsql.dll
Syntax
[Serializable]
public class NpgsqlException : DbException, ISerializable
Constructors
|
Improve this Doc
View Source
NpgsqlException()
Declaration
|
Improve this Doc
View Source
NpgsqlException(SerializationInfo, StreamingContext)
Initializes a new instance of the NpgsqlException class with serialized data.
Declaration
protected NpgsqlException(SerializationInfo info, StreamingContext context)
Parameters
Type | Name | Description |
---|---|---|
SerializationInfo | info |
The SerializationInfo that holds the serialized object data about the exception being thrown. |
StreamingContext | context |
The StreamingContext that contains contextual information about the source or destination. |
|
Improve this Doc
View Source
NpgsqlException(String, Exception)
Initializes a new instance of the NpgsqlException class with a specified error message and a reference to the inner exception that is the cause of this exception.
Declaration
public NpgsqlException(string message, Exception innerException)
Parameters
Type | Name | Description |
---|---|---|
String | message |
The error message that explains the reason for the exception. |
Exception | innerException |
The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. |
|
Improve this Doc
View Source
NpgsqlException(String)
Initializes a new instance of the NpgsqlException class with a specified error message.
Declaration
public NpgsqlException(string message)
Parameters
Type | Name | Description |
---|---|---|
String | message |
The message that describes the error. |
Properties
|
Improve this Doc
View Source
BatchCommand
If the exception was thrown as a result of executing a DbBatch, references the DbBatchCommand within
the batch which triggered the exception. Otherwise null.
Declaration
public NpgsqlBatchCommand BatchCommand { get; set; }
Property Value
Type | Description |
---|---|
NpgsqlBatchCommand |
Remarks
|
Improve this Doc
View Source
IsTransient
Specifies whether the exception is considered transient, that is, whether retrying the operation could
succeed (e.g. a network error or a timeout).
Declaration
public virtual bool IsTransient { get; }
Property Value
Type | Description |
---|---|
Boolean |
Implements
Вопрос:
Я использую Entity Framework, поэтому считаю, что я должен поймать NpgsqlException
поскольку это поставщик данных.NET для PostgreSQL. Поэтому позвольте сказать, что я делаю запрос к контексту. Если таблица не существует в базе данных PostgreSQL, я хочу уловить созданное исключение, а затем вручную создать его. Ниже приведен пример того, как объект вставлен, и я попытался использовать обработку ошибок для создания таблицы, если это необходимо:
try
{
return _context.Set(entityType).Add(entity);
}
catch (NpgsqlException)
{
CreateEntityTable(entity); //a private method I made
return _context.Set(entityType).Add(entity);
}
Проблемы:
-
Я не уверен на 100%, я должен поймать NpgsqlException
-
Я хочу быть уверенным, что если исключение выбрано, это потому, что таблица не существует. Я просмотрел документацию по ошибкам PostgreSQL и код ошибки 42P01 – это неопределенная таблица. Я считаю, что хочу использовать это, но как? Я просмотрел членов класса NpgsqlException и нашел ErrorCode. Однако, что тип int. Было бы неплохо, если бы я мог изменить код выше, чтобы выглядеть следующим образом:
try { return _context.Set(entityType).Add(entity); } catch (NpgsqlException ex) { if (ex.ErrorCode.Equals(42P01)) { CreateEntityTable(entity); //a private method I made return _context.Set(entityType).Add(entity); } }
Но я не уверен, что это имеет смысл (я даже не знаю, как 42P01 может быть int).
Любая помощь будет оценена по достоинству.
Лучший ответ:
Вы захотите использовать свойство Code для NpgsqlException, поскольку оно будет содержать код ошибки PostgreSql.
Обновление вашего примера:
try
{
return _context.Set(entityType).Add(entity);
}
catch (NpgsqlException ex)
{
if (ex.Code == "42P01")
{
CreateEntityTable(entity); //a private method I made
return _context.Set(entityType).Add(entity);
}
}
В стороне, я бы предположил, что вы не выполняете обновления схемы в своем обычном коде. Только делайте что-то подобное в установщике или при запуске в качестве обновления.
Alex1333 0 / 0 / 0 Регистрация: 15.06.2017 Сообщений: 6 |
||||
1 |
||||
15.06.2017, 22:17. Показов 10058. Ответов 5 Метки нет (Все метки)
Здравствуйте, у меня возникла такая проблема. На сервере PostgreSQL 9.3 создана база данных, в ней 5 таблиц. При попытке отображения данных из бд в datagridview возникает ошибка Добавлено через 1 минуту
__________________
0 |
YuryK 1039 / 855 / 335 Регистрация: 08.12.2016 Сообщений: 3,283 |
||||
16.06.2017, 00:01 |
2 |
|||
Решениепотому что ORDER — это служебное слово SQL
а вы таблицу так назвали. Полагаю 4 остальные называются SELECT, FROM, DELETE и INSERT?
1 |
Alex1333 0 / 0 / 0 Регистрация: 15.06.2017 Сообщений: 6 |
||||||||
16.06.2017, 05:56 [ТС] |
3 |
|||||||
Спасибо помогло) Не знал.Остальные называю по другому. Ещё есть вопрос.
Добавлено через 3 часа 35 минут
0 |
YuryK 1039 / 855 / 335 Регистрация: 08.12.2016 Сообщений: 3,283 |
||||
16.06.2017, 11:12 |
4 |
|||
Не тот код скинул в том хоть смысл был, а ошибка из-за того, что дату, указываемую как текстовую константу, тоже надо обрамлять кавычками
вот и соберите такую строку а как второй вариант кода сформирует нужную строку, вообще не представляю.
1 |
1187 / 917 / 367 Регистрация: 02.09.2012 Сообщений: 2,793 |
|
16.06.2017, 16:15 |
5 |
и еще заметил, что отсутствует слово VALUES после перечисления имен столбцов.
0 |
0 / 0 / 0 Регистрация: 15.06.2017 Сообщений: 6 |
|
18.06.2017, 17:21 [ТС] |
6 |
Спасибо, разобрался.
0 |