how can i write "in( select" method in linq?
I'm trying to convert :
UPDATE ActualAmountsByLocation SET isCustomerItem=1 WHERE ItemBarcode IN (SELECT barcode FROM StockMaterials WHERE barcode=#Barcode AND ownership=1)
I've tried like this:
Array stockMaterials = ( from s in stockMovementCtx.StockMaterials where s.barcode == Barcode && s.ownership ==1 select s).ToArray();
actualAmountsByLocation = (from a in stockMovementCtx.ActualAmountsByLocations
where a.ItemBarcode.Contains(stockMaterials)
select a).First();
To get an IN query you need to reverse the sense of the contains. Also, no need to materialize the first query, IMO.
var stockMaterials = from s in stockMovementCtx.StockMaterials
where s.barcode == Barcode && s.ownership ==1
select s;
actualAmountsByLocation = (from a in stockMovementCtx.ActualAmountsByLocations
where stockMaterials.Contains( a.ItemBarcode)
select a).First();
You're almost there.
Remove the .ToArray call to prevent the query from being executed directly, and make your stockMaterials variable of type IQueryable<StockMaterial>.
This what you're looking for?
ActualAmountsByLocation = StockMaterials.Where(s => s.barcode == Barcode && s.ownership == 1).ToArray();
var stockMaterials = (from s in stockMovementCtx.StockMaterials
where s.barcode == Barcode && s.ownership == 1
select s).ToArray();
var actualAmountsByLocation = (from a in stockMovementCtx.ActualAmountsByLocations
where stockMaterials.Contains(a.ItemBarcode)
select a).First();
Hopefully this code example below is helpful for you
// these are using linq methods
var barcodes = stockMovementCtx.StockMaterials
.Where(s => s.barcode == Barcode && s.ownership == 1)
.Select(s => s.barcode);
var amounts = stockMovementCtx.ActualAmountsByLocations
.Where(a => barcodes.Contains(a.ItemBarCode))
.FirstOrDefault();
// if you would like to use the query expressions instead, here they are
//var barcodes = from s in stockMovementCtx.StockMaterials
// where s.barcode = Barcode && s.ownership == 1
// select s.barcode;
//var amounts = (from a in stockMovementCtx.ActualAmountsByLocations
// where barcodes.Contains(a.ItemBarCode.Contains)
// select a).FirstOrDefault();
// helpful to use FirstOrDefault if you are not sure that the query will return a result
if (amounts != null) {
// change value
amounts.IsCustomerItem = 1;
// update database
stockMovementCtx.SubmitChanges();
}
Making update on LinQ is so easy thing, check the code block below for example.
var user = (from s in dataContext.USERS
Calling Users Table, and setting where condition.
where s.UserId.Equals(id)
select s).FirstOrDefault();
I want to make change on user email.(Dont forget this: If you call with ToList(), you need to control list count to avoid exception for ex: if(user.Count > 0)..)
Updating user:
s.EmailAddress = serkan#serkanhekimoglu.com;
dataContext.SubmitChanges();
and your data will be updated after SubmitChanges();
Related
I am new to LINQ queries and want to use FirstOrDefault in my existing LINQ query.
List<vUserAll> employee = (from o in db.vUsersAll
where (o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) && o.Domain == "dExample"
select o).ToList();
What's the correct way to do this?
This can be simplified further as:
var filtered = db.vUsersAll.FirstOrDefault(u => u. Field == filter);
If the above mentioned is the case, then you can use a labmda as in the following:
var firstOrDefaultResult = db.vUsersAll.Where(o=>
(o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName)
&& o.Domain == "dExample").FirstOrDefault()
If you want to use the same above expression then,
vUserAll employee = (from o in db.vUsersAll
where (o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) && o.Domain == "dExample"
select o).FirstOrDefaul();
It's a lot easier if you only use LINQ extensions. For example,
var filtered = all users.Where(u => u. Field == filter).FirstOrDefault();
How can I build a single Linq statement where it check returns all records unless the param is passed? If param is empty then ignore specific 'where'.
I have tried using IsNullOrEmpty within the WHERE but I get an error.
Here are the NON-REQUIRED form field for searching for Invoices.
Invoice Id, Check Number, State Issued
var invoices = ctx.Invoices; <-- get all invoiced
if (inputInvoiceId > 0)
invoices = from i in invoices
where i.id == inputInvoiceId
select i;
if (!string.IsNullOrEmpty(inputCheckNumber))
invoices = from i in invoices
where i.checkNumber == inputCheckNumber
select i;
if (!string.IsNullOrEmpty(inputState))
invoices = from i in invoices
where i.state == inputState
select i;
You could build your query by conditionally appending where clauses like this:
var invoices = ctx.Invoices.AsQueryable();
if (inputInvoiceId > 0)
invoices = invoices.Where(x => x.id == inputInvoiceId);
if (!string.IsNullOrEmpty(inputCheckNumber))
invoices = invoices.Where(x => x.checkNumber == inputCheckNumber);
if (!string.IsNullOrEmpty(inputState))
invoices = invoices.Where(x => x.state == inputState);
return invoices.ToList();
Each additional where clause further filters your results, but the query itself won't be executed (nor any data retrieved) until you call ToList().
What #GrantWinney said will work. Alternatively, you can deal with it in a single query, which may or may not have query compilation/cache benefits if you are concerned about such things:
// Query short-circuit parameters
var invoiceNotSpecified = inputVoiceId == 0;
var checkNumberNotSpecificed = String.IsNullOrEmpty(inputCheckNumber);
var stateNotSpecified = String.IsNullOrEmpty(inputState);
// Query
var invoices = from i in ctx.Invoices
where (invoiceNotSpeficied || i.id == inputInvoiceId) &&
(checkNumberNotSpecified || i.checkNumber == inputCheckNumber) &&
(stateNotSpecified || i.state == inputState)
select i;
This is the SQL query I have written:
select * from Addresses a
join ProviderAddresses pa on a.address_k = pa.address_k
where pa.provider_k = 'ABC123'
and pa.active = 1
and a.active = 1
and pa.addresstype_rtk = 'HOME'
And this is the LINQ query I wrote for it:
public IQueryable<Addresses> GetAddressesesForProvider(string provider_k, string addresstype_rtk)
{
var query = from a in this.Context.Addresses
join pa in this.Context.ProviderAddresses on a.Address_K equals pa.Address_K
where pa.AddressType_RTK == addresstype_rtk
&& pa.Active == true
&& a.Active == true
select a;
return query;
}
But it is wrong. The LINQ one return thousands of records and the SQL one returns only one record.
It is IQueryable because later I need to go through its results with a for-each loop.
In the SQL I am passing hard coded values for testing but in my code for me LINQ method I also pass the same hard coded values so that is not the issue.
Looks like you may have just missed adding the provider_k condition to the where;
public IQueryable<Addresses> GetAddressesesForProvider(string provider_k, string addresstype_rtk)
{
var query = from a in this.Context.Addresses
join pa in this.Context.ProviderAddresses on a.Address_K equals pa.Address_K
where pa.Provider_K == provider_k &&
pa.AddressType_RTK == addresstype_rtk &&
pa.Active == true &&
a.Active == true
select a;
return query;
}
I have a LINQ query:
var list = from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t;
How can I modify this query to select just five results from the database?
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
The solution:
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
This can also be achieved using the Lambda based approach of Linq;
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
[Offering a somewhat more descriptive answer than the answer provided by #Ajni.]
This can also be achieved using LINQ fluent syntax:
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
Note that each method (Where, OrderBy, Take) that appears in this LINQ statement takes a lambda expression as an argument. Also note that the documentation for Enumerable.Take begins with:
Returns a specified number of contiguous elements from the start of a
sequence.
Additional information
Sometimes it is necessary to bind a model into a view models and give a type conversion error. In this situation you should use ToList() method.
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5).ToList();
Just thinking you might be feel unfamiliar of the sequence From->Where->Select, as in sql script, it is like Select->From->Where.
But you may not know that inside Sql Engine, it is also parse in the sequence of
'From->Where->Select', To validate it, you can try a simple script
select id as i from table where i=3
and it will not work, the reason is engine will parse Where before Select, so it won't know alias i in the where. To make this work, you can try
select * from (select id as i from table) as t where i = 3
I'm writing a linq query in query syntax and I'm wondering how to add another where clause.
Basically, I have the following:
var test = from t in MyDC.TheTable
where t.UserID == TheUserID
where t.DateDone.Date == TheDate.Date
select new MyModel {.....};
TheTable has a column called LinkedID and this column is also in another table called ColorStatus (a number between 1 and 10). I'm looking to write the where clause "where the LinkedID in the ColorStatus table is less than 7".
Thanks.
Just a suggestion on improving the statement you have. You can actually merge the two where conditions into a single one. && means "AND"
Where t.UserID == TheUserID && t.DateDone.Date = TheDate.Date
Your information "another table called ColorStatus" doesn't make sense here.
var test = from t in MyDC.TheTable
where t.UserID == TheUserID
&& t.DateDone.Date == TheDate.Date
&& t.LinkedID < 7
select new MyModel {.....};
Probably I didn't get your idea, here is an example of join may help you.
var test = from t in MyDC.TheTable
join x in MyDC.ColorStatus
on t.LinkedID == x.LinkedID
where t.UserID == TheUserID
&& t.DateDone.Date == TheDate.Date
&& x.AnotherField == 1
select new MyModel {.....};