wit*_*623 9 sqlite entity-framework-core uwp
我在 UWP 中使用 EF Core 和 SQLite。我试图通过调用 DbContext.Database.Migrate() 进行迁移,但我总是得到Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: 'table "Tags" already exists'.'.
我确定该表不存在,因为我检查了 bin/debug 文件夹,没有数据库文件。即使我签入错误的文件夹,也不应该有问题,不是吗?
我已经多次删除 Migrations 文件夹,但我认为这不是导致此异常的原因。
这是 DbContext 代码。
public class AppDbContext : DbContext
{
public DbSet<Word> Words { get; set; }
public DbSet<WordMeaning> WordMeanings { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<WordTag> WordTags { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=Vocabulary.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// PK declaration
modelBuilder.Entity<Word>()
.HasKey(w => w.Text);
modelBuilder.Entity<WordMeaning>()
.HasKey(wm => new { wm.WordText, wm.WordClass });
modelBuilder.Entity<Tag>()
.HasKey(t => t.Name);
modelBuilder.Entity<WordTag>()
.HasKey(wt => new { wt.WordText, wt.TagName });
// relation declaration
modelBuilder.Entity<Word>()
.HasMany(w => w.WordMeanings)
.WithOne(wm => wm.Word)
.HasForeignKey(wm => wm.WordText)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<WordTag>()
.HasOne(wt => wt.Tag)
.WithMany(t => t.WordTag)
.HasForeignKey(wt => wt.TagName);
modelBuilder.Entity<WordTag>()
.HasOne(wt => wt.Word)
.WithMany(w => w.WordTag)
.HasForeignKey(wt => wt.WordText);
}
}
Run Code Online (Sandbox Code Playgroud)
和所有模型代码。
public class Tag
{
public string Name { get; set; }
public string Description { get; set; }
public List<WordTag> WordTag { get; set; }
}
public class Word
{
public string Text { get; set; }
public WordClass WordClasses { get; set; }
public DateTime AddedDate { get; set; }
public List<WordMeaning> WordMeanings { get; set; }
public List<WordTag> WordTag { get; set; }
}
public class WordMeaning
{
public string WordText { get; set; }
public string Definition { get; set; }
public string Example { get; set; }
public WordClass WordClass { get; set; }
public Word Word { get; set; }
}
public class WordTag
{
public Word Word { get; set; }
public Tag Tag { get; set; }
public string WordText { get; set; }
public string TagName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
不要同时使用EnsureCreatedand Migrate,只迁移到足以创建和迁移数据库的程度
using (var db = new DBContext())
{
//db.Database.EnsureCreated(); Don't use
db.Database.Migrate();
}
Run Code Online (Sandbox Code Playgroud)
@Gert Arnold 说,你的 SQLite 数据库文件(Vocabulary.db)应该默认创建LocalFolder。您应该能够找到Tag已在 上创建表的数据库C:\Users\{username}\AppData\Local\Packages\{your app package name}\LocalState)。Package.appxmanifest->Packing->Package name您可以在项目中找到的包名称。有关 uwp 应用程序上的文件访问的更多详细信息,请参阅文件、文件夹和库。
有关 uwp 实体框架的更多详细信息,请参阅UWP - 新数据库。
| 归档时间: |
|
| 查看次数: |
6269 次 |
| 最近记录: |