简体   繁体   English

如何使用 EF 从导航属性中仅选择特定列

[英]How to select only particular columns from navigation properties using EF

I'm trying to select only 2 columns from the navigation properties but unable to do it, can anyone let me know how can I achieve this?我试图从导航属性中只选择 2 列,但无法做到,谁能告诉我如何实现这一点?

It works good default way(selecting all columns) :它的默认方式很好(选择所有列):

  var productreceipts = db.productreceipts.Include(p => p.employee).Include(p => p.productmaster).Include(p => p.vendor);

What I want:我想要的是:

Select only 2 columns form each of employee, productmaster, vendor tables.仅从员工、产品主管、供应商表中的每个表中选择 2 列。

I know how to select if I have only one table:如果我只有一张桌子,我知道如何选择:

var productreceipt = db.productreceipts.Select(p => new { p.ReceiptId, p.ReceivedBy });

EDIT : I want to select all properties of first table(productreceipts) and only a few selected from others.编辑:我想选择第一个表(产品收据)的所有属性,并且只从其他表中选择一些。

Any help will be much appreciated.任何帮助都感激不尽。

Thanks in advance.提前致谢。

You can use like :你可以使用像:

  var productreceipts = db.productreceipts.Include(p => p.employee).
                                          .Select(p => new { propertyName = p.productmaster.SomeProperty })

Try this:尝试这个:

var productreceipt = db.productreceipts
    .Select(p => 
    new {   productreceipts_prop_1 = p.productreceipts_prop_1,
            productreceipts_prop_2 = p.productreceipts_prop_2,
            productreceipts_prop_3 = p.productreceipts_prop_3,
            productreceipts_prop_4 = p.productreceipts_prop_4,

            employee_prop_1 = p.employee.employee_prop_1,
            employee_prop_2 = p.employee.employee_prop_2,

            productmaster_prop_1 = p.productmaster.productmaster_prop_1,
            productmaster_prop_2 = p.productmaster.productmaster_prop_2,

            vendor_prop_1 = p.vendor.vendor_prop_1,
            vendor_prop_1 = p.vendor.vendor_prop_1,
    });

EDIT:编辑:

There is no need to use the .Include() You can directly use the navigator property to retrieve the data.不需要使用.Include()就可以直接使用 navigator 属性来检索数据。

If you have lazy loading enabled then you can directly use如果您启用了延迟加载,则可以直接使用

.Select(p => new { ProductId = p.productmaster.ProductId }

else you will have to take inner join and select individual columns in single select.否则,您将必须采用内部联接并在单选中选择单个列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM