[英]Create SQL View With Entity Framework 6 Code First
I am new to Entity Framework 6 Code First and am trying to perform what I thought would be a simple task. 我是Entity Framework 6 Code First的新手,我正在尝试执行我认为简单的任务。 I want to create a SQL View and then have an Entity in my database context that I can use to query the view.
我想创建一个SQL视图,然后在我的数据库上下文中有一个Entity,我可以使用它来查询视图。
I have tried articles such as this but the key difference in my case is that the SQL View is not an existing view coming from another existing database. 我曾尝试如文章本但对我来说最关键的区别是,SQL视图是不是从另一个现有的数据库即将现有视图。
I examined the proposition made in this article but it seems like overkill to me that I would need to create some extension methods to do something as simple as create a view/entity combo and use it in my database context. 我检查了本文中提出的命题,但对我来说似乎有点过分,我需要创建一些扩展方法来做一些简单的事情,比如创建一个视图/实体组合并在我的数据库上下文中使用它。
Am I missing something? 我错过了什么吗? I know it would be much easier if I weren't using Code First but please keep in mind it's Code First and I am trying to create a view, not reuse one from an existing database.
我知道如果我不使用Code First会更容易,但请记住它是Code First,我正在尝试创建一个视图,而不是重用现有数据库中的视图。
Colin and Kevin, Thank you for the link to your answer on the other post and your concise answer. 科林和凯文,感谢您在另一篇文章中找到答案的链接和简明的答案。 I have used several resources to finally create a queryable entity based on a new SQL view.
我已经使用了几个资源来最终基于新的SQL视图创建可查询实体。 Just in case anyone else is new to EF 6.0 Code First and is just getting their feet wet, I do have a few steps that will hopefully benefit others in the future.
为了防止其他人对EF 6.0 Code First不熟悉并且刚刚开始行动,我确实会采取一些措施,希望将来能够让其他人受益。
It still surprises me that I need to do all of this custom work to create a view and map it to an entity with Code First, but at the end of the day it was helpful in getting me started on migrations as you can only rely on the "automatic migrations" for so long anyways. 我仍然感到惊讶的是,我需要完成所有这些自定义工作来创建视图并将其映射到具有Code First的实体,但在一天结束时,它有助于我开始迁移,因为您只能依赖无论如何,“自动迁移”已经很久了。
您可以手动添加sql以创建迁移视图,然后根据您的第一个链接使用它。
The answer in the link provided by Colin does the job. 科林提供的链接中的答案完成了这项工作。
In case there are lots of views to be created, it can be a good idea to save the view queries in separate files and add them in a resource (.resx) file instead of hard-coding the sql queries in the Migration Up() method. 如果要创建大量视图,最好将视图查询保存在单独的文件中,并将它们添加到资源(.resx)文件中,而不是在Migration Up()中对sql查询进行硬编码方法。
For eg 例如
public override void Up()
{
Sql("ResourceFileName.ResourceName");
}
instead of hard coding like 而不是硬编码
{
Sql("EXEC ('CREATE View [dbo].[ClientStatistics] AS --etc");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.