C# 如何使用 EF 代码优先的 POCO 创建视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13593845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a view using EF code-first POCO
提问by Chuck Norris
That simple. I need to create a Viewusing Code First. I found nothing about this on google nor SO. Is there a way to accomplish this?
就那么简单。我需要使用 Code First创建一个视图。我在 google 和 SO 上都没有发现任何关于此的信息。有没有办法做到这一点?
I need that view to be created and queried using linq, so it's not a solution to create it using an script on Database creation, for example:
我需要使用 linq 创建和查询该视图,因此在数据库创建时使用脚本创建它不是解决方案,例如:
var results = from c in db.Customer
join v in db.MyView on c.Id equals v.Id
select c;
A work around is also acceptable. I need a way to query entities against non-constant/ non-entities values.
解决方法也是可以接受的。我需要一种方法来针对非常量/非实体值查询实体。
采纳答案by Anatolii Gabuza
You cannot create views with EF Code First approach. If you want to create view then execute creation sql script in Seedmethod. But you'll still not be able to map entity to this view, except hacking model by creating and droping table with same name as your view will have.
您不能使用 EF Code First 方法创建视图。如果要创建视图,则在Seed方法中执行创建 sql 脚本。但是您仍然无法将实体映射到此视图,除非通过创建和删除与您的视图具有相同名称的表来破解模型。
Some helpful links:
一些有用的链接:
回答by Fred
you must manually create the view, just like AnatoliiG stated. (Adding index to a table).
您必须手动创建视图,就像 AnatoliiG 所说的那样。(向表添加索引)。
You add the name of the view as an attribute to your class
您将视图的名称作为属性添加到您的类
[Table("UserDTO")]
public class UserDTO
{
/* Class code here */
}
You can create an empty migration by specifying the -IgnoreChanges attribute at the end
您可以通过在末尾指定 -IgnoreChanges 属性来创建空迁移
Add-Migration MigrationName -IgnoreChanges
This gives you an empty migration script that you can manually modify.
这为您提供了一个可以手动修改的空迁移脚本。
You can use your db context to execute your code in your migration script
您可以使用数据库上下文在迁移脚本中执行代码
public partial class editUserDTO : DbMigration
{
public override void Up()
{
string script =
@"
CREATE VIEW dbo.UserDTO
AS SELECT p.PersonId AS UserId, p.FirstName, p.LastName, u.UserName
FROM dbo.Users u
INNER JOIN dbo.People p ON u.PersonId = p.PersonId";
BloggingContext ctx = new BloggingContext();
ctx.Database.ExecuteSqlCommand(script);
}
public override void Down()
{
BloggingContext ctx = new BloggingContext();
ctx.Database.ExecuteSqlCommand("DROP VIEW dbo.UserDTO");
}
}
回答by John
Just a heads up, in EF 6.1 (not sure if in earlier or not) there is now a Code First from Databaseoption you can use and it will map to views as well.
提醒一下,在 EF 6.1(不确定是否更早版本)中,Code First from Database您现在可以使用一个选项,它也将映射到视图。
I personally have mine in a separate junk project so I can just take out the code I want from it and not impact my project that actually uses the database. To use it Add a New file to your project -> Data -> ADO.NET Entity Data Model
我个人将我的代码放在一个单独的垃圾项目中,因此我可以从中取出我想要的代码,而不会影响我实际使用数据库的项目。使用它Add a New file to your project -> Data -> ADO.NET Entity Data Model
Then select the Code First From Databaseoption and select your views (and other tables if you want)
然后选择该Code First From Database选项并选择您的视图(如果需要,还可以选择其他表格)
It will create it as a Table mapping like Fred was talking about in his answer, but will do all the code for you which is nice. You'll probably want to change the indexes and ordering though.
它会将其创建为表映射,就像 Fred 在他的回答中所说的那样,但会为您完成所有代码,这很好。不过,您可能想要更改索引和排序。
Then just call Sql(@"YOUR VIEW CREATE SQL HERE")in your Upand add a Sql(@"DROP STATEMENT HERE")in your Down
然后只需调用Sql(@"YOUR VIEW CREATE SQL HERE")您的Up并Sql(@"DROP STATEMENT HERE")在您的Down
回答by Todd
A lot of good insights from the official issues thread of EF7:
来自EF7 官方问题线程的很多很好的见解:
1) Don't have a DbSet, and instead have a property or extension method
1)没有 DbSet,而是有一个属性或扩展方法
A) Property
A) 财产
class YourContext
{
public IQueryable<YourView> YourView
{
get
{
return this.Database.SqlQuery<YourView>("select * from dbo.YourView");
}
}
}
B) Extension Method
B) 扩展方法
static class YourContextExtensions
{
public static IQueryable<YourView>(this YourContext context)
{
return context.Database.SqlQuery<YourView>("select * from dbo.YourView");
}
2) Apparently, you can have the migration process ignore certain dbsets
2)显然,您可以让迁移过程忽略某些数据库集
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
if (IsMigration)
modelBuilder.Ignore<YourViewTable>();
...
}
(All the above are untested)
(以上均未经测试)
回答by Debasis
You cannot create a view from EF Code First ,you should add the script in the 'seed' script to pre populate the view .
您不能从 EF Code First 创建视图,您应该在“种子”脚本中添加脚本以预填充视图。

