如何在代码优先实体框架中使用视图 [英] how to use views in code first entity framework

查看:22
本文介绍了如何在代码优先实体框架中使用视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何先在实体框架代码中使用数据库视图,

How can I use the database view in entity framework code first,

推荐答案

如果和我一样,您只对映射来自其他数据库(在我的情况下为 erp)的实体感兴趣,以便将它们与您的应用程序特定的实体相关联,然后您可以像使用表格一样使用视图(以相同的方式映射视图!).显然,如果您尝试更新该实体,并且视图不可更新,则会出现异常.该过程与正常(基于表)实体的情况相同:

If, like me, you are interested only in mapping entity coming from an other database (an erp in my case) to relate them to entities specific of your application, then you can use the views as you use a table (map the view in the same way!). Obviously, if you try to update that entities, you will get an exception if the view is not updatable. The procedure is the same as in the case of normal (based on a table) entities:

  1. 为视图创建一个POCO类;例如 FooView
  2. 在 DbContext 类中添加 DbSet 属性
  3. 使用 FooViewConfiguration 文件为视图设置不同的名称(在构造函数中使用 ToTable("Foo");)或设置特定属性

  1. Create a POCO class for the view; for example FooView
  2. Add the DbSet property in the DbContext class
  3. Use a FooViewConfiguration file to set a different name for the view (using ToTable("Foo"); in the constructor) or to set particular properties

public class FooViewConfiguration : EntityTypeConfiguration<FooView>      
{
    public FooViewConfiguration()
    {
        this.HasKey(t => t.Id);
        this.ToTable("myView");
    }
}

  • 将 FooViewConfiguration 文件添加到模型构建器,例如覆盖 Context 的 OnModelCreating 方法:

  • Add the FooViewConfiguration file to the modelBuilder, for example ovveriding the OnModelCreating method of the Context:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new FooViewConfiguration ());
    }
    

  • 这篇关于如何在代码优先实体框架中使用视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆