简体   繁体   中英

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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