Map View - Entity Framework

Asked

Viewed 1,323 times

2

I know it has been asked something similar, but in the answers I found said that to map the view should put the Dataannotation [Table("view name")] or configure 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 went around the application I had an error like "The model backing the context has changed Since the database was created."

So in the Nuget Package Console I came in with

Update-Database -force -verbose

Then I had a mistake that there is already an object called "Users". There on the console even showed a "CREATE TABLE USERS ...." IE, he tried to create the table.

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

  • Created a view in the database?

  • 1

    Yes. I created the direct view in Management Studio

  • Ahhh good, I thought you were confusing view with model (MVC).

  • You know that EF will try to create a table in the database and not a view, right?

  • I did. I saw in the package console the instruction to create the table.

1 answer

4


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

Create a second reading-only context, like this:

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

Put the DbSet who will read the view bank:

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

    public DbSet<UserView> UsersView { get; set; }
}
  • 1

    thanks @gypsy creating a new context worked

  • What if I have classes related to this context? in my case for example I have a user named class that is managed by another application, ie in this my app, I can not do Inserts/Updates/Delete, but I need to save the related user, how to treat, since they are in separate contexts?

  • @Alexbecker It will not be a relationship handled by the Entity Framework. One way to solve would be to create a Database View in the database where the EF context is mapped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.