[英]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.我正在使用 asp.net 内核和数据库优先方法的实体框架来开发 web 应用程序,我遇到了一些脚手架问题。 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.每当我对数据库进行更改时,我希望能够更新我的上下文和我的模型,并且似乎使用
Scaffold-DbContext
命令是这样做的方法。 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.我试图通过将我的模型从数据库中搭建到一个名为 DbModels 的文件夹中来解决这个问题,并将我当前在代码中使用的所有模型保存在 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.然后我让模型中的每个 class 都继承自 DbModels 中相应的 class,这样我就可以使用
Scaffold-DbContext
更新 DbModels 中的模型,并在模型中保留我想要的任何其他代码。 But the problem I run into with this is that I cannot do something like DerivedModel d = DbContext.BaseModel.First();
但是我遇到的问题是我不能做像
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.我觉得好像 inheritance 必须成为解决这个问题的必要条件,但是我一直无法让它发挥作用。
Partial class is your friend here.部分 class 是您的朋友。 Just make sure the partial view has the same name as the auto-generated class and everything should be fine.
只需确保局部视图与自动生成的 class 具有相同的名称,一切都应该没问题。
public partial class TableName
{
public string PropertyName {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.