Joe Ruder
Joe Ruder

Reputation: 2194

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

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

Upvotes: 3

Views: 1704

Answers (4)

Marty
Marty

Reputation: 545

As pointed out by ErikEJ this won't work:

You could use a metadata class along with a partial class (example copied from doc):

using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

[MetadataType(typeof(UserInfoMetaData))]
public partial class UserInfo
{

}

public class UserInfoMetaData
{
    [Required()]
    public object FirstName;
}

This would then sit in a separate file, that won't be touched by code-gen. Note that you don't need to add all properties to the metadata class and their type doesn't matter - but the names must match.

There are some ways however how to make it work, see this SO item which itself is based on this ASP.NET Forums question. In the ASP.net link, there is also a suggestion to make the validation on the view model instead of the data classes. So that might be a possibility to consider.

Upvotes: 0

ErikEJ
ErikEJ

Reputation: 41749

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://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#scaffold-dbcontext

Upvotes: 2

ErikEJ
ErikEJ

Reputation: 41749

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.

Upvotes: 2

markorial
markorial

Reputation: 445

I understand that it was created DB first but after initial creation of the models if you do model changes before changes in db it would be best to create migrations from code that way all the changes to the models will be replicated in the database.

Upvotes: 0

Related Questions