1

I'm creating a SQL View on my Configuration Seed

protected override void Seed(QuiverContext context)
{
    context.Database.ExecuteSqlCommand(DatabaseScripts.Views.MyView);
}

Now I want to add a DBSet to my DbContext that represents my View. I read that one can do this using then the Entity like a regular table.

So I tried but it requires me to add a migration which I did, but then the update-database command fails when creating the view since a table is created first.

Community
  • 1
  • 1
Hugo Hilário
  • 2,848
  • 2
  • 27
  • 43
  • You should also understand that you can't just treat a View like a table... there are a lot of issues with Views, particularly since they may not be updatable, and EF can't tell what the primary key might be so it treats all non-nullable fields as primary keys. In general, I find using views with EF to be unworkable, but some people find them acceptable. – Erik Funkenbusch Apr 14 '15 at 15:26

1 Answers1

1

It looks like you're trying to create a view in your Seed method. This isn't the way to create a view (remember the seed method runs every time ANY migration runs).

The better way to be would be to add a migration. This will create a code file containing CreateTable lines, which will make your table. Just remove these lines, and replace them with a call to create your view.

You can execute custom Sql inside a migration using the Sql command, for example...

Sql("CREATE VIEW myView.....");

If you want to make things a bit more robust, you can create an extension for migrations which allows you to call CreateView.

Richard
  • 29,854
  • 11
  • 77
  • 120
  • Well I still can use the ``seed``, I just need to make sure my migration ``Up`` doesn't do anything. Having this logic on ``seed`` has some benefits since all my scripts will be together there (sp's, views, triggers) and every-time a change needs to be done to these scripts I don't need to pollute my migrations. But still I understand the advantages of having it on the migration, thank you so much. – Hugo Hilário Apr 14 '15 at 16:28
  • I tend to use the `Sql` method for all of the things you mention - the only reason I would use Seed is if you actually need to use EF, rather than adding things using SQL. Putting code in the migrations means you don't have to worry about checking whether they should run. – Richard Apr 14 '15 at 16:55