如何在代码优先实体框架中使用视图

发布于 2024-12-05 07:45:31 字数 1436 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

屋檐 2024-12-12 07:45:31

如果像我一样,您只对映射来自其他数据库(在我的例子中是 erp)的实体感兴趣,以便将它们与您的应用程序特定的实体相关联,那么您可以像使用表一样使用视图(将视图映射到同样的方式!)。显然,如果您尝试更新该实体,并且视图不可更新,您将收到异常。
该过程与普通(基于表)实体的情况相同:

  1. 为视图创建 POCO 类;例如FooView

  2. 在 DbContext 类中添加 DbSet 属性

  3. 使用 FooViewConfiguration 文件为视图设置不同的名称(在构造函数中使用 ToTable("Foo"); 或设置特定属性

    public class FooViewConfiguration : EntityTypeConfiguration;      
    {
        公共 FooViewConfiguration()
        {
            this.HasKey(t => t.Id);
            this.ToTable("myView");
        }
    }
    
  4. 将 FooViewConfiguration 文件添加到 modelBuilder,例如覆盖 Context 的 OnModelCreating 方法:

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

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. 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");
        }
    }
    
  4. Add the FooViewConfiguration file to the modelBuilder, for example overriding the OnModelCreating method of the Context:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new FooViewConfiguration ());
    }
    
薆情海 2024-12-12 07:45:31

这可能是一个更新,但要首先将视图与 EF 代码一起使用,只需将 [Table("NameOfView")] 添加到类的顶部,一切都应该正常工作,而不必经历其他人正在经历的所有麻烦。此外,您还必须将其中一列报告为 [key] 列。下面是我的示例代码来实现它。

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SomeProject.Data
{
    [Table("SomeView")]
    public class SomeView
    {
        [Key]
        public int NameID { get; set; }
        public string Name { get; set; }
    }
}

这是上下文的样子

using System.Data.Entity;

namespace SomeProject.Data
{
    public class DatabaseContext : DbContext
    {
        public DbSet<SomeView> SomeViews { get; set; }
    }
}

This may be an update but to use views with EF Code first simply add [Table("NameOfView")] to the top of the class and all should work right without having to go through all the hoops everyone else is going through. Also you will have to report one of the columns as a [key] column. Here is my sample code below to implement it.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SomeProject.Data
{
    [Table("SomeView")]
    public class SomeView
    {
        [Key]
        public int NameID { get; set; }
        public string Name { get; set; }
    }
}

And here is what the context looks like

using System.Data.Entity;

namespace SomeProject.Data
{
    public class DatabaseContext : DbContext
    {
        public DbSet<SomeView> SomeViews { get; set; }
    }
}
撩心不撩汉 2024-12-12 07:45:31

如果您想要的只是一堆非规范化对象,那么您可能只需在 DbContext 类中创建一个公共的仅获取 IQueryable 属性。

get 中,您返回 Linq 结果以将非标准化值投影到非标准化对象中。这可能比编写数据库视图更好,因为您正在编程,您不受仅使用 select 语句的限制。而且它是编译时类型安全的。

请小心,不要触发像 ToList() 调用这样的枚举,这会破坏延迟查询,最终您可能会从数据库中获取一百万条记录,并在应用程序服务器上过滤它们。

我不知道这是否是正确的方法,但我尝试过并且它对我有用。

If all you want is a bunch of de-normalized objects, then you might just created a public get-only IQueryable<TDenormolized> property in your DbContext class.

In the get you return a Linq result to project the de-normoalized values into your de-normalized objects. This might be better than writing a DB View because you are programming, you are not limited by only using select statements. Also it's compile time type safe.

Just be careful not trigger enumerations like ToList() calls, that will break the deferred query and you may end up with getting a million records back from the database and filter them on your application server.

I don't know if this is the right way, but I tried and it works for me.

痴骨ら 2024-12-12 07:45:31

我知道这是一个老问题,这里有很多答案,但是当我使用 this 答案时,我被迫遇到一个问题当我在包管理器控制台中使用 update-database 命令时发生错误:

数据库中已有一个名为“...”的对象。

我使用以下步骤来解决这个问题:

  1. 在程序包管理器控制台中运行此命令:Add-migration intial
  2. 在 Migrations 文件夹下,您可以找到 ..._intial.cs 文件,打开它并注释或删除与您的类相关的任何命令您现在想要映射
  3. ,通常可以使用 update-database 命令对模型进行任何其他更改,

希望它有所帮助。

I know this is an old question and there is many answers here, but I forced to an issue when I use this answer and an error occurred when I use update-database command in Package Manager Console:

There is already an object named '...' in the database.

and I use these steps to solve this issue:

  1. run this command in Package Manager Console:Add-migration intial
  2. Under the Migrations folder, you can find ..._intial.cs file, open it and comment or delete any command related to your class you want to map
  3. now you can normally use update-database command for any other change to your models

hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文