0

I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework. I copied the model class and changed its name and added it to the context:

public class ViewIncomingCheck
{
    [Key]
    public int Id { get; set; }
     //...
}

public class CheckDataContext : DbContext
{
    public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
    //...
}

now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.

How can I use this view in my code?

Edit

My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.

Community
  • 1
  • 1
Alireza Noori
  • 14,961
  • 30
  • 95
  • 179
  • For the moment EF core doesn't support View but you can work with view using Queries like this example : https://stackoverflow.com/questions/36012616/working-with-sql-views-in-entity-framework-core – Alaaeddine HFIDHI Apr 05 '19 at 08:57

1 Answers1

1

According to what I have done in my project:

  • First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; } to your DbConext

  • Now create a migration something called ViewDbSetAdded

  • Remove all the code from the both Up and Down method and it will look like as follows:

Migration Code:

public partial class ViewDbSetAdded : DbMigration
{
    public override void Up()
    {

    }

    public override void Down()
    {

    }
}
  • Now run update-database command and it will run an empty migration.
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114