LinqToSql:如何创建符合 DRY 的投影?
只是想知道是否有一种方法可以从 LINQ to SQL 投影类型中删除一些重复内容。
示例:
表:地址
字段:AddressID、HouseNumber、街道、城市、州、邮政编码以及其他 20 个
类 MyAddress:AddressID、HouseNumber、 Street (Only 3 fields)
LINQ:
from a in db.Addresses select new MyAddress { AddressID = a.AddressID, HouseNumber = a.HouseNumber, Street = a.Street }
上面的查询工作得很好,我明白为什么这样的东西会返回每行中的所有 20 多个字段:
from a in db.Addresses select new MyAddress(a); class MyAddress { public MyAddress(Address a) { this.AddressID = a.AddressID, this.HouseNumber = a.HouseNumber, this.Street = a.Street } }
这引出了我的问题:
是否可以实现某种辅助函数或扩展方法可以从 LINQ 模型“映射”到 MyAddress,但只返回查询结果中的必要字段而不是所有字段?
Just wondering if there is a way to take some of the repitition out of a LINQ to SQL projected type.
Example:
Table: Address
Fields: AddressID, HouseNumber, Street, City, State, Zip, +20 more
Class MyAddress: AddressID, HouseNumber, Street (Only 3 fields)
LINQ:
from a in db.Addresses select new MyAddress { AddressID = a.AddressID, HouseNumber = a.HouseNumber, Street = a.Street }
The above query works perfectly, and I understand why something like this will return all 20+ fields in each row:
from a in db.Addresses select new MyAddress(a); class MyAddress { public MyAddress(Address a) { this.AddressID = a.AddressID, this.HouseNumber = a.HouseNumber, this.Street = a.Street } }
Which leads me to my Question:
Is it possible to implement some kind of helper function or extension method to "map" from the LINQ model to MyAddress yet only return the necessary fields in the query result rather than all of the fields?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该查询将仅选择生成的 SQL 中请求的字段。
重用该类型的函数将如下所示:
可以这样使用:
我认为函数将如下所示:
That query will only select the requested fields in the resulting SQL.
A function to re-use the type will look like:
This can be used like this:
I think a function would look something like: