简体   繁体   中英

Issues With LINQ to SQL Query

I am having trouble getting one of my LINQ to SQL queries to work correctly. I have three tables setup as follows:

Vendors id - primary key

Manufacturers id - primary key

ManufacturerVendorRelationships id - primary key manufacturer_id - foreign key to manufacturer.id vendor_id - foreign key to vendor.id

I am trying to write a LINQ to SQL query that will fetch the Vendors that are not currently related to a given manufacturer. For example, the following table data should only result in 2 vendors for the manufacturer with ID of 1. Can someone please help me with the LINQ to SQL for this example? Right now, the application is doing this logic. Thanks in advance.

Vendors
ID
1
2
3
4
5

Manufacturers
ID
1
2
3
4
5

ManufacturerVendorRelationships
ID               ManufacturerID                   VendorID
1                1                                1
2                1                                2
3                1                                3

Maybe something like this:

var result=(
        from v in db.Vendors
        where !db.ManufacturerVendorRelationships
                 .Select(s=>s.VendorID)
                 .Contains(v.ID)
        select v
    );

Or if you want it like a field:

var result=(
        from v in db.Vendors
        select  new
        {
            v.ID,
            HasManufacturer=db.ManufacturerVendorRelationships
                           .Select(s=>s.VendorID)
                           .Contains(v.ID)
        }
    );

where db is the linq data context

int id= 1;
var result = 
dc.Vendors
  .Where(v => !dc.ManufacturerVendorRelationships
                 .Any(rel => rel.VendorId == v.Id && rel.ManufacturerId == id));

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