entity framework code first and view mapping

[亡魂溺海] 提交于 2019-12-10 21:55:33

问题


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)


回答1:


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



回答2:


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>();
    }
}


来源:https://stackoverflow.com/questions/17383459/entity-framework-code-first-and-view-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!