简体   繁体   中英

Entity Framework context and model inheritance when scaffolding in database first approach

I am working on a web application using asp.net core with entity framework with the database first approach, and I am running into some problems with scaffolding. I would like to be able to update my context and my models whenever I make a change to the database, and it seems like using the Scaffold-DbContext command is the way to do it. However, when running this command, I run into the problem that any extra code I've written into my models is going to be overwritten.

I have tried to solve this problem by scaffolding my models from the database into a folder called DbModels, and keeping all of the models I am currently using in my code in Models. I then made every class in Models inherit from its corresponding class in DbModels, so that I can update the models in DbModels using Scaffold-DbContext and keep any other code I want in Models. But the problem I run into with this is that I cannot do something like DerivedModel d = DbContext.BaseModel.First(); because base objects cannot be assigned to derived objects.

I feel as if inheritance has to be integral to the solution to this problem, however I have been unable to make it work.

Partial class is your friend here. Just make sure the partial view has the same name as the auto-generated class and everything should be fine.

public partial class TableName 
{
    public string PropertyName {get; set;} 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM