Answer the question
In order to leave comments, you need to log in
Why do I get an error when creating a SQLite database in C#?
Created two models and a data context. I made a migration (Add-Migration Initial) and executed the command to create a database (Update-Database), the database was created, but an error occurs when it is opened. The question is why, I broke my whole head, I can’t work normally with SQLite and EF.
Here are the models and context:
class Phone
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
[ForeignKey("CompanyId")]
public virtual Company Company { get; set; }
public Phone(string Name, string Title)
{
this.Name = Name;
this.Title = Title;
}
public override string ToString()
{
return $"{Name} {Title}";
}
}
class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Phone> Phones { get; set; }
public override string ToString()
{
return Name;
}
}
class Context : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Phone> Phones { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(@"Data Source=MobileDB.db;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>().ToTable("Companies");
modelBuilder.Entity<Phone>().ToTable("Phones");
}
}
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Companies",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Companies", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Phones",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(nullable: true),
Title = table.Column<string>(nullable: true),
CompanyId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Phones", x => x.Id);
table.ForeignKey(
name: "FK_Phones_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Phones_CompanyId",
table: "Phones",
column: "CompanyId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Phones");
migrationBuilder.DropTable(
name: "Companies");
}
Answer the question
In order to leave comments, you need to log in
Maybe you haven't closed the studio and it's locking the file, or maybe you're using version 2 instead of version 3.
Check it all out.
UPD, add a constructor and check whether the tables were created in it.
public Context()
{
Database.EnsureCreated();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question