Generating a SQL view from EF 6.1 code first
Asked Answered
S

1

5

I just changed my application from Database first to code first! What a great improvement in deploying!. But now i have the following problem. I generated my Code-first model from my database, but after recreating the database from the generated code, my views from my database are generated like tables!

How do I generate my views from code first? and/or map them to my entities if I need to generate them manually?

EDIT.

Luke McGregor's post certainly brought me close. Yes it generates the views now. But the migrations don't work.

When trying to do a Update-Database statement the initial output is that there still are code changes.

I therefore executed the Add-Migration xxx Command and fired the Update-Database command again.

EDIT 2:

Resolving a few differences between my Code-first code and the view's SQL code solved this issue!

Soupspoon answered 9/4, 2014 at 13:55 Comment(4)
Possible duplicate of #7461765Displease
@CraigW. i think this is a different question this relates to creation not BAUPremillennialism
The second half of the question relates to mapping your entities to existing views (i.e. "and/or map them to my entities if i need to generate them manually?"), which is what he'll have to do. I can't even wrap my head around how code-first would generate views, it still needs a table behind the view to store/retrieve the data from.Displease
possible duplicate of Mapping Database Views to EF 5.0 Code First w/MigrationsWarms
P
10

You will need to create a manual migration with some raw SQL in it eg something along the lines of the below

public partial class MyMigration: DbMigration 
{ 
    public override void Up() 
    { 
        Sql("CREATE VIEW......"); 
    } 
}
Premillennialism answered 9/4, 2014 at 14:2 Comment(3)
Use Sql("EXEC ('CREATE View......." to avoid problems with "first in batch" problems. You can't put in "GO" in a migration because it's not a sql commandWarms
LukeMcgregor, You certainly brought me close to a solution. @Colin, thanks for the EXEC addition. It certainly works to generate the views for meSoupspoon
This works, I've noticed some other answers to similar questions create a DbContext and run the update view command rather than calling Sql(). This has the unfortunate side effect of actually updating the DB even when calling update-database -scriptAlarum

© 2022 - 2024 — McMap. All rights reserved.