SQLite代码优先onModelCahnge如何保持数据库中的旧数据(SQLite code

编程入门 行业动态 更新时间:2024-10-11 23:26:41
SQLite代码优先onModelCahnge如何保持数据库中的旧数据(SQLite code-first onModelCahnge how to keep the old data from databse)

我是Sqlite和EF的新手。

我用一些模型类创建了一个DbContext,它将在app start上创建一个本地数据库。 应用程序运行时,数据库将更新。

当我在模型中更改某些内容(例如:将新属性添加到类中)并运行应用程序时,整个数据库将从头开始重新创建。 所以我丢失了我保存的数据。

即使模型发生变化,我如何保留旧数据。

对于Ex:

Database.table1 ID | Name 1 | abc 2 | xyz

当我向table1类添加新的prop时,它使用空数据重新创建表,如果可能的话,我需要这样的东西。

Database.table1 ID | Name | NewProp 1 | abc | Null 2 | xyz | Null

i'm new to Sqlite and EF.

i created a DbContext with some model classes which will create a local database on app start. Database will get updated while application running.

When i change something in model (ex: add new property to a class) and run the application, the whole database is recreating from scratch. so i'm loosing my saved data.

How can i keep the old data even though the model changes.

For Ex:

Database.table1 ID | Name 1 | abc 2 | xyz

when i add new prop to table1 class, its recreating table with empty data, where i need something like this if possible.

Database.table1 ID | Name | NewProp 1 | abc | Null 2 | xyz | Null

最满意答案

数据库初始化程序是导致在模型更改时重新创建数据库的原因。 因此,您可以通过将初始化程序设置为null来禁用它:

Database.SetInitializer<MyContext>(null);

这当然意味着您需要手动使数据库与模型匹配。 另一种选择是使用不丢弃并创建数据库的初始化程序。 看起来SqlLite有一个项目: https : //github.com/msallin/SQLiteCodeFirst那么你可以使用SqliteCreateDatabaseIfNotExists。

最后,您可以使用迁移。 看起来不像开箱即用,所以你需要第三方工具。 SQLite的实体框架MigrationSqlGenerator

The database initializer is what causes the database to be recreated on a model change. So you can disable the initializer by setting it to null:

Database.SetInitializer<MyContext>(null);

This of course means you will need to manually make your database match the model. Another option is to use an initializer that doesn't drop and create the database. Looks like there is a project here for SqlLite: https://github.com/msallin/SQLiteCodeFirst So then you could use SqliteCreateDatabaseIfNotExists.

Finally, you could use migrations. Doesn't look like that's supported out of the box so you would need a third party tool for that. Entity Framework MigrationSqlGenerator for SQLite

更多推荐

本文发布于:2023-08-04 02:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1408975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库中   代码   数据   SQLite   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!