How can I add column to an existed sqlite database?

melon NG 291 Reputation points
2022-07-08T06:41:53.853+00:00

Currently the new version of my program needs to add a column to the database for a new feature.

The program is made by WPF and EFCore. And also, the database I am using is SQLite.

The program needs to check whether the column existed. If not, then it will create a new column.

In addition, the old data of the database should be kept

How can I achieve this by EFCore?

Thank you.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
695 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
{count} votes

Accepted answer
  1. Jack J Jun 24,281 Reputation points Microsoft Vendor
    2022-07-12T10:07:29.933+00:00

    @melon NG , based on my test, I suggest that you could try the following code to add a column to the database if the column does not exist.

    220316-image.png

    We could call it in button_click event directly.

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Viorel 111.8K Reputation points
    2022-07-08T08:17:45.813+00:00

    Consider the ExecuteSqlRaw function: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.executesqlraw.

    Execute a statement like this: ALTER TABLE MyTable ADD COLUMN newColumn int null.

    Intercept and ignore the errors that say "column already exists".

    0 comments No comments