是否有一种简单的方法来处理仅在某些时候映射的属性?例如:
我有产品表和产品实体。大多数时候我使用LINQ to SQL来执行相当于:
select * from products where...
但是,偶尔我会手动编写一个更像是的SQL查询:
select products.*, someOtherVal, anotherVal from products join....
据我所知,我无法将someOtherVal
和anotherVal
添加到我的实体,因为它们并不总是映射到列。
注意:我意识到正确设置我的所有实体和关系并且不使用Entity.SqlQuery()可能更好。我只是想知道现在是否有快速实现目标的方法。我将在以后继续将我的应用程序转换为EF时进行改进。
答案 0 :(得分:1)
使用匿名类型。
您创建的IQueryable变量在您枚举之前不会执行。如果IQueryable中的Expression仅使用产品的某些属性,则只在查询中请求这些属性:
html
head
body
table.table.table(border='1')
thead
tr
th ID
th Name
th Age
th City
th Department
tbody
each row in rows
tr
td=row.id
td=row.name
td=row.age
td=row.city
td=row.department
td button(type='submit',onclick='edit("#{row.id}")') Edit
script.
function edit(d){
var val = confirm ("Do you want to edit the record ?");
if (val==true){
return true;
}
};
注意:仍未执行查询。 现在如果您执行查询,例如由于ToList(),则只在SQL中选择所请求的参数
var myQuery = mydbContext.Products // join products and OtherTable
.Join(myDbContext.OtherTable,
product => product.SomeForeignKey, // from product use SomeForeignKey
otherThing => otherThing,PrimaryKey, // from otherTable use PrimaryKey
(product, otherThing) => new // when these key Match
{ // create an anonymous object
X = product.X, // with the Properties you want
Y = product.Y,
Z = otherThing.Z,
};