Entity Framework Code First 和视图映射

3

我有一个使用Code First的应用程序;在搜索部分,我需要从3个表及其关联表中收集信息,因此我创建了一个视图;由于Code First没有语法来创建视图(我认为是这样,请告诉我如果我错了),因此我使用了纯SQL脚本; 在模型创建中,为了防止EF创建与表(VIEW_SEARCH)同名的表,我执行了以下操作:

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

在尝试从视图中获取数据时,应用程序运行良好,直到出现问题...

'SearchContext'上下文的模型与创建数据库时不同。考虑使用Code First Migrations更新数据库(http://go.microsoft.com/fwlink/?LinkId=238269


试试这个:https://dev59.com/fmEi5IYBdhLWcg3w4Pnr#35876571 - Mr. DMX
请尝试我的解决方案。它可以防止将标记为视图的表生成迁移。 - giokoguashvili
2个回答

1
这个错误表示您的模型文件与数据库中的内容不一致。要使其一致,请转到程序包管理器控制台,键入Enable-Migrations,然后键入Add-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

也许我没有提供足够的信息;迁移已启用,如果模型更改,则数据库正在重新生成!!! - Navid Kianfar
关于组合:我需要它们合并成这样:`public class SearchResult { public SearchResult() { Query = null; Total = TotalPages = 0; Page = 1; Result = new List<View_Search>(); } public int Page { get; set; } public string Query { get; set; } public List Result { get; set; } public int Total { get; set; } public int TotalPages { get; set; } }` - Navid Kianfar

0

我实际上正在使用Entity Framework "Code First"和视图进行编程,我的做法是这样的:

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

读取数据时出现错误:值不能为空(不知道“值”是什么……) - wtf512

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接