พอดีลองเล่น EF สักหน่อย หลักๆจะใช้ Dapper เอา แล้วมีเคสมือลองไปแก้ ลองเปลี่ยน
- จาก Database First มาเป็น Code First
- แก้ DbContext มาเป็น IdentityDbContext
ที่นี่พอลอง Run จะเจอ Error
Unable to create a 'DbContext' of type ''. The exception 'The entity type 'IdentityUserLogin<string>' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Solution
- Old Code
public partial class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Your Logic
}
}- New Code
public partial class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); << Add this line
// Your Logic
}
}Note: จริงๆ ไม่ควร Database First มาเป็น Code First บน Production นะครับ
- ส่วนตัวเอง ยังหา Solution แปลงจาก Database First มาเป็น Code First โดยที่ไม่ลบ และ Generate ใหม่ ส่วนตัวที่ลอง ก่อนแก้ Entity
dotnet ef migrations add initial dotnet ef migrations update
- ที่ลองส่วนสุด EF กับ PostgreSQL ยังเจอ Error ในส่วนของ relation อยู่
- ถ้าใน Lab ที่ลองเล่นของผม ใช้วิธ๊ลบทิ้ง แล้ว initial DB ใหม่ แล้ว Dump คืนกลับไป
Discover more from naiwaen@DebuggingSoft
Subscribe to get the latest posts sent to your email.



