【问题标题】:entity framework code first and view mapping实体框架代码优先和视图映射
【发布时间】:2013-06-29 18:31:20
【问题描述】:

我有一个应用程序首先使用代码;在搜索部分,我必须从 3 个表及其相关表中收集信息,所以我做了一个视图;并且由于没有代码首先创建视图的语法(我认为是这样;如果我错了请告诉我)我使用纯 SQL 脚本; 在创建模型以防止 EF 创建与表 (VIEW_SEARCH) 同名的表时:

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

任何方式应用程序都可以正常工作,直到您尝试从视图中获取数据然后 BANG...

支持“SearchContext”上下文的模型在创建数据库后发生了变化。考虑使用 Code First 迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)

【问题讨论】:

标签: entity-framework view ef-code-first code-first


【解决方案1】:

这个错误只是说明您的模型文件中的内容与您的数据库中的内容不一致。 要使其保持一致,请转到包管理器控制台并键入 Enable-Migrations,然后添加-Migration yourMigrationName 和 Update-Database。错误应该消失。

如果您想合并 3 个表中的数据,您可以简单地创建一个 ViewModel。

假设您有 3 个模型:Book、Author、BookStore,并且您希望在一个视图中包含所有信息。你创建 ViewModel

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

然后您在多合一视图的顶部添加

@model myNamespace.MyViewModel

并访问类似的项目

Model.Book.title
Model.Author.name
Model.BookStore.isClosed

【讨论】:

  • 也许我能提供足够的信息;如果模型更改,迁移已启用并且数据库正在重新生成!!!
  • 关于组合:我需要它们像这样合并:public class SearchResult { public SearchResult() { Query = null; Total = TotalPages = 0; Page = 1; Result = new List&lt;View_Search&gt;(); } public int Page { get; set; } public string Query { get; set; } public List&lt;View_Search&gt; Result { get; set; } public int Total { get; set; } public int TotalPages { get; set; } }
【解决方案2】:

我实际上是在使用实体框架“代码优先”和视图,我这样做的方式是这样的:

1) 创建一个类

[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) 将类添加到上下文中

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

【讨论】:

  • 读取数据时出错:值不能为空(不知道Value是什么...)
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 2011-04-21
  • 2012-05-18
相关资源
最近更新 更多