我如何编写自己的对数据库实体进行操作的ef核心函数

问题描述 投票:0回答:1

我正在尝试向ef core添加一个新的自定义函数,以便可以在数据库实体上使用。

我需要在每个实体上添加自己的count实现。

db.xyz.count() does not work for me.

它对我不起作用,因为它由于行数太慢。

我想拥有一个自定义函数,该函数从另一个视图带来计数。

类似:

db.xyz.customcount();

我尝试使用ef核心扩展方法:

namespace xyz.Helpers
{
    public static class CustomCountExtension:DbContext
    {
        public static int CustomCount() => {....};

    }
}

但是这个函数,我需要它针对另一个视图进行查询,该视图存储了每个实体的计数。

。i.e

Myview:

table | row  |
______________

xyz   | n    |

当我调用xyz.customcount()时,我需要它返回在表中的行数= xyz。

这可能吗。

实施上述想法是否更好?

我正在使用:

。net core 2.1ef core 2.2

c# .net entity-framework asp.net-core ef-core-2.0
1个回答
0
投票

您可以将实体直接映射到视图,并像表一样查询它。

public class MyView
{
    public string Table { get; set; }
    public int Row { get; set; }
}

然后将其定义为DbQuery,而不是DbSet中的DbContext

public virtual DbQuery<MyView> MyView { get; set; }

然后使用OnModelCreating()而不是.Query().Entity()方法将其映射到您的视图:

protected override view OnModelCreating(ModelBuilder modelBulder)
{
    //... Other tables

    modelBuilder.Query<MyView>(query =>
    {
        query.ToView("MyView");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.