entity framework code first and view mapping

2019-07-16 01:17发布

I have a application using code first; in search section I have to gather information from 3 tables and their related tables so I made a view; and since there is no syntax for code first to create view (I think so; please let me know if I'm wrong) I used pure SQL script; on model creating to prevent EF to create a table with same name as table (VIEW_SEARCH) I did :

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Ignore<View_Search>();
    }

any ways application works fine until you try to get data from the view then BANG...

The model backing the 'SearchContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)

2条回答
你好瞎i
2楼-- · 2019-07-16 01:46

This error simply says that what you have in your model file is inconsistent with what you have in your database. To make it consistent go to Package Manager Console and type Enable-Migrations, then Add-Migration yourMigrationName and Update-Database. The error should disappear.

If you want to combine data from 3 tables you can simply create a ViewModel.

Let's say you have 3 models: Book, Author, BookStore and you want to have all information in one view. You create ViewModel

public class MyViewModel 
{
   public Book myBook {get; set;}
   public Author myAuthor {get; set;}
   public BookStore myBookStore {get; set;}
}

Then you add at the top of your all-in-one-view

@model myNamespace.MyViewModel

and access items like

Model.Book.title
Model.Author.name
Model.BookStore.isClosed
查看更多
相关推荐>>
3楼-- · 2019-07-16 02:01

I'm actually working with Entity Framework "Code First" and views, the way I do it is like this:

1) Create a class

[Table("view_name_on_database")]
public class ViewClassName {
    // View columns mapping
    public int Id {get; set;}
    public string Name {get; set;}
    // And a few more...
}

2) Add the class to the context

public class ContextName : DbContext {
    // Tables
    public DbSet<SomeTableClassHere> ATable { get; set; }
    // And other tables...

    // Views
    public DbSet<ViewClassName> ViewContextName { get; set; }

    // This lines help me during "update-database" command
    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        // Remove comments before "update-database" command and 
        // comment this line again after "update-database", otherwise 
        // you will not be able to query the view from the context.
        // Ignore the creation of a table named "view_name_on_database"
        modelBuilder.Ignore<ViewClassName>();
    }
}
查看更多
登录 后发表回答