如何将相同的逻辑应用于多个实体对象
我的实体数据模型中有大约 20 个不同的报告表,它们都有一些公共字段(例如 start_date 和 end_date)。当我的报告应用程序提取给定报告的数据时,我做的第一件事是过滤表中今天的日期。这意味着我在整个代码(VB)中都有与此类似的代码块:
Dim data =
From r in _context.Rpt1
Where
r.start_date <= Now And
r.end_date >= Now
似乎应该有一种方法可以将此逻辑放入一个函数中,该函数可以让我过滤任何表,但我不知道如何构建它。我可以这样做:
Public Function FilterByDate(data As IEnumerable) As IEnumerable
Return From d In data Where d.start_date <= Now And d.end_date >= Now
End Function
但由于返回值是通用的 IEnumerable,我失去了在特定报告列上早期绑定的所有优势。
有没有一种方法可以创建一个通用函数,可以将一些逻辑应用于不同的对象并返回该特定对象而不是通用对象?或者,有没有办法将返回值转换回特定的实体对象类型?还有其他方法可以解决此类问题吗?只是寻找想法或看待问题的不同方式。
I have about 20 different report tables in my Entity Data Model that all have a few common fields (like start_date and end_date). When my reporting application pulls data for a given report, the first thing I do is filter the table for today's date. This means I have code blocks similar to this throughout my code (VB):
Dim data =
From r in _context.Rpt1
Where
r.start_date <= Now And
r.end_date >= Now
It seems like there should be a way to put this logic into a function that will let me filter any table, but I can't figure out how to structure it. I could do this:
Public Function FilterByDate(data As IEnumerable) As IEnumerable
Return From d In data Where d.start_date <= Now And d.end_date >= Now
End Function
but since the return value is a generic IEnumerable I lose all the advantages of early binding on the specific report columns.
Is there a way to create a single generic function that can apply some logic to different objects and return that specific object instead of a generic one? Alternatively, is there a way to cast the return value back to the specific entity object type? Is there another way to attack this type of problem? Just looking for ideas or different ways of looking at the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以利用生成的实体是部分类这一事实,通过让任何(或全部,如果符合要求)实现一个接口
IFoo
来公开“通用”属性,例如start_date
和end_date
。然后,您可以编写一个通用过滤方法(C# 代码,抱歉):
由于通用参数类型约束,这将接受任何有意义的可查询类型,但由于通用参数类型,仍然允许您返回与传入的完全相同的类型扣除。
You can take advantage of the fact that the generated entities are partial classes by having any (or all, if they fit the bill) implement an interface
IFoo
that exposes the "common" properties likestart_date
andend_date
.You can then write a generic filtering method (code in C#, sorry):
This will accept any meaningful type of queryable thanks to the generic parameter type constraint, but still allow you to return the exact same type as passed in thanks to generic argument type deduction.