Take the following classes:
public class Person
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}
public class Instructor : Person
{
public DateTime HireDate { get; set; }
}
public class Student : Person
{
public DateTime EnrollmentDate { get; set; }
}
Then "dotnet ef database update" will create a single table named Person with a Discriminator column (table-per-hierarchy inheritance).
CREATE TABLE [dbo].[Person](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Discriminator] [nvarchar](max) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[HireDate] [datetime2](7) NULL,
[EnrollmentDate] [datetime2](7) NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
)

Question: Is it possible to recreate the three classes from the Person database table using "dotnet ef dbcontext scaffold"?
Thanks
I won't be as bold as to go ahead and say 'NO'. Instead, I'm just saying that so far I've always done it manually, because I personally have not come across any method of specifying this for the automated scaffolding and I can't imagine how such a tool could work.
The first problem is that the discriminator column can be any arbitrary column. While this could be solved by simply specifying the name of the discriminator with a command line switch and then generating a class for every distinct value, there's a bigger problem: there's no way to tell which column belongs to which class. The only thing that the scaffolder could do is put everything that's not nullable to the base class. But what about the nullable columns? Are they nullable because they are part of the base class and are specified as nullable (explicitly or by convention), or are they nullable because they are in one of the descendant classes? And if they are in the descendant classes, in which one? There's no way to tell WHY a column is null; is it because it is in another class, or because it has no value at the moment in the record that represents the object?
But, to be fair, it's not that much work to redesign the scaffolded code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With