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

大城市里の小女人 提交于 2019-12-10 18:52:48

问题


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:


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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/53574640/add-modifications-to-your-model-when-using-ef-core-db-first-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!