Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework code first and view mapping

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)

like image 279
Navid Kianfar Avatar asked Aug 24 '26 01:08

Navid Kianfar


1 Answers

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
like image 64
a'' Avatar answered Aug 25 '26 21:08

a''



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!