Add modifications to your model when using EF Core DB First Design

c# entity-framework entity-framework-core

Question

My team uses Db first design. We create the database, then create the model using the Scaffold-DbContext command.

The problem is when we need to modify the model and then do a recreation.

public partial class UserInfo
{
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public DateTime RecordCreated { get; set; }
}

Upon invoking a Scaffold-DbContext with the -Force it will remove the [Required] from it.

Should I be looking at using a ViewModel, creating partial classes or what?

Very early on in using EF core 2.1 so any help would be greatly appreciated.

Joe

1
3
12/1/2018 8:10:12 PM

Accepted Answer

If you are using database first, you make the database column required (NOT NULL), and then run scaffolding again, not the other way round. When scaffolding, you can choose to generated Attributes over fluent configuration, if you do that, you will get the "Required" attribute added (for reference types).

The switch for Scaffold-Dbontext is -DataAnnotations

https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#scaffold-dbcontext

1
12/2/2018 8:39:58 AM

Popular Answer

Use EF Core Power Tools, it generates a partial method for OnModelCreating, and then use the fluent API in a new partial class to set the Required option instead of attributes.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow