Mapping View - Entity Framework

2

I know that something like this has already been asked, but in the answers I found, I wanted to map the view to put the DataAnnotation [Table ("view name"]) or configure it in the Fluent API

I created a view in the database called "Users". So I created a class called UserView

[Table("Users")]
public class UserView 
{
  public string EmailAddress { get; set;} 
  ......
}

Then in my DbContext I created DbSet

public DbSet<UserView> Users { get; set; }

When I rounded the application I had an error of type "The model backing the context has changed since the database was created."

Then in the Nuget Package Console I joined

  

Update-Database -force-verbose

Then I had an error that already exists an object called "Users" . There on the console even showed a "CREATE TABLE USERS ...." ie it tried to create the table.

I'm using Automatic Migrations. How could I map this existing view and / or create it if it does not exist?

    
asked by anonymous 03.06.2016 / 13:56

1 answer

4

This is totally wrong . If you have a context managed by the Entity Framework, you can not map read-only objects to it.

Create a second read-only context, like this:

public class ReadOnlyContext: DbContext
{
    public ReadOnlyContext()
        : base("name=DefaultConnection")
    {
        Database.SetInitializer<ReadOnlyContext>(null);
    }
}

Put in it the DbSet that will read the bank view :

public class ReadOnlyContext: DbContext
{
    public ReadOnlyContext()
        : base("name=DefaultConnection")
    {
        Database.SetInitializer<ReadOnlyContext>(null);
    }

    public DbSet<UserView> UsersView { get; set; }
}
    
03.06.2016 / 23:29