Hi,@Kamyab Faghih. Welcome to Microsoft Q&A.
Creating a database using DBContext in a .NET 8 ClassLibrary Project
Example(Assume that the database is Sql Server and the development tool is Visual Studio):
1.Create a .NET 8 ClassLibrary Project
2.Install Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Design, and Microsoft.EntityFrameworkCore.Tools through Nuget
3.Add entity class
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
4.Add DbContext Class (Write your database connection string)
public class MyDbContext:DbContext
{
public MyDbContext() { }
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Write your database connection string");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.ToTable("User");
entity.HasKey(p => p.Id).HasName("PK_User");
entity.Property(p => p.Id)
.HasColumnName("id")
.HasColumnType("int").ValueGeneratedNever();
entity.Property(p => p.Name)
.HasColumnName("name");
});
}
}
5.Set the current project as startup project
6.Execute the command to generate the database
Way 1(Ensure that the current project can be built successfully):
a.Open Developer PowerShell-> Enter the current project
b.If dotnet ef is not installed, you need to execute this command
dotnet tool install --global dotnet-ef
c.Creating Migrations
dotnet ef migration add init
d.Update the database
dotnet ef database update
Way 2(Ensure that the solution can be built successfully):
a. Open Tools->NuGet Package Manager-> Package Manager Console
b. Set the Default Project as the current project
c. Creating Migrations
Add-Migration Init
d. Update the database
Update-Database
You can check your program against the above examples. If you can provide a simple example that causes the error, I will be able to answer your question more accurately.
If the answer is the right solution, please click "Accept Answer" and kindly 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.