如何使用EF创建视图或计算表

时间:2017-11-21 11:32:00

标签: sql-server asp.net-mvc entity-framework

我在ASP.NET MVC应用程序中使用Entity Framework Code First。如何在数据库中创建查看以使用JOIN从以下两个表中获取记录。

Sub RemoveExtras()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Dim c As Integer, i As Integer, ws As Worksheet
Dim dict As Object


For Each ws In Worksheets

    Set dict = CreateObject("Scripting.Dictionary")
    'Find Last column
    c = ws.UsedRange.Columns.Count

    'Loop backwards
    For i = c To 2 Step -1

        'If column does not exist in dictionary, then add it
        If Not dict.Exists(ws.Cells(2, i).Value) Then
            dict.Add ws.Cells(2, i).Value, 1
        Else
        'Otherwise delete column
            ws.Columns(i).Delete Shift:=xlToLeft
        End If

    Next i
    Set dict = Nothing
Next

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic



End Sub

2 个答案:

答案 0 :(得分:0)

您可以创建一个模型作为视图所需的返回类型,然后创建 使用Sql方法迁移内部的视图:

public partial class Migration : DbMigration
{
  public override void Up()
  {
      this.Sql("CREATE VIEW dbo.MyView AS (etc)");
  }

  public override void Down()
  {
      this.Sql("DROP VIEW dbo.MyView");
  }
}

在dbContext中将实体映射到视图没有任何问题:

public class MyDbContext : DbContext
{
  public DbQuery<MyModelView> MyView
  {
     get
     {
        // Don't track changes to query results
        return Set<MyModelView>().AsNoTracking();
    }
  }
}

答案 1 :(得分:0)

通过使用Database.ExecuteSqlCommand(),您可以触发任何类型的DDL命令。

using(var edb = new EmployeeDB()
{
edb.Database.ExecuteSqlCommand("CREATE VIEW MyView AS SELECT TOP 3 
e.First_Name, e.Last_Name, e.Gender, e.Salary, d.Name as Deparment_Name, 
d.Location as Department_Location FROM tblEmployees e JOIN tblDepartments d on 
e.DepartmentId=d.DepartmentId");
}