use "from" property in the linq - linq

in my class i have a property with name "from" but i can't use it in my linq statement ?
is there any solution or i have to change my property name ?
lst1 = (from p in db.adv where p.isShowInMainPage && p.isShowInHeader && (p.from <= DateTime.Now) orderby p.id descending select p);
lst2= (from p in db.adv where p.isShowInMainPage && !p.isShowInHeader orderby p.id descending select p);
when i use p.from compile error occure :
Error 14 ; expected
in the SQL we could use [] ([from]) . is there any similar thing in LINQ

At (#from) in the beginning should work in C#, in VB.NET you use [from]

You could do as #Ales says and use an # symbol in front of the property name. Alternatively you could rename your property to From using Pascal casing - the .NET design guidelines on capitalisation conventions suggest using Pascal casing for properties.

Related

Linq where clause invalid

var advocacy = (from c in svcContext.CreateQuery("lead")
join a in svcContext.CreateQuery("product")
on c["transactioncurrencyid"] equals a["transactioncurrencyid"]
where a["capg_billingtimeframe"].Equals(126350000)
select new
{
dues = c["capg_calculatedduesbilling"],
product = c["capg_primaryproduct"],
listprice = a["price"],
eligibility = c.FormattedValues["capg_eligibility"]
});
That is my linq query and it is giving me the error: Invalid 'where' condition. An entity member is invoking an invalid property or method.
I have looked online everywhere and done their suggestions. I am not using Xrm.cs because late binding can be faster. I have tried using the == operand and I have tried doing (int) and Convert.ToInt32(a["capg_billingtimeframe"]) and even converting everything to a string. I will say that a["capg_billingtimeframe"] I know is an object (that's why I did those conversions.
I'm guessing by that integer that capg_billingtimeframe is an optionset. If it is, you need to cast it like this:
where ((OptionSetValue)a["capg_billingtimeframe"]).Value == 126350000
I used early bound and for getting the local I wrote:
OptionSetValue branch = this.InputTargetEntity.Attributes.Contains("capg_calculatorutilized") ? (OptionSetValue)this.InputTargetEntity["capg_calculatorutilized"] : (OptionSetValue)this.TargetPreImage["capg_calculatorutilized"];
I then had to get the Optionsets.cs using crmsvcutil and writing:
if (branch.Value == (int)capg_calculatorrequired.SectionA)
Works like a charm.

LINQ .Count() not defined for int

I have the below LINQ statement, and get the error " 'int' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'int' could be found ( are you missing a using directive or assembly reference?) "
var queryFuture = from pqv in context.OrderPrintQueue_View
join od in context.Order_Details on pqv.confirmId equals od.ConfirmId
join pp in context.Product_Price on od.priceId equals pp.priceId
join p in context.Products on pp.productId equals p.ProductID
select new { p.stationId, inProc = 0, OrderLinesCount = od.recId.Count() };
od.recId.Count() is the portion that is returning an error. I'm very new to LINQ (have been using it for about 2 days) and am a novice programmer. The answers I have found all say to include the system.core assembly reference, and of course, the System.Linq using. I have all of those so I'm not sure what the deal is. I am using WPF with .NET 4, EF, and RIA services and the MVVM pattern.
recID is of type int, not IEnumerable<?>. Count() is only defined on IEnumerable<?>. You will ned a group by statement:
var queryFuture = from pqv in context.OrderPrintQueue_View
join od in context.Order_Details on pqv.confirmId equals od.ConfirmId
join pp in context.Product_Price on od.priceId equals pp.priceId
join p in context.Products on pp.productId equals p.ProductID
group od by od.recId into orders
select new { p.stationId, inProc = 0, OrderLinesCount = orders.Count() };
Note: I'm not sure of this combination of group by and join will work out, as I usually only use the method chains. You might have to adjust on the operators, however you'll need a group by in any case.
Why would you want to get the count for an integer? You are probably getting a single value back, not a collection, which it seems is what you are expecting.

compare the dates with linq

I have this code:
i.SpesaVitto = db.TDP_NotaSpeseSezB.Where(p => p.GiornoFine == null &&
((DateTime)p.Giorno).Date == ((DateTime)i.Data).Date &&
p.MissioneID == missioneID).Sum(p => p.Costo);
If i launch it i obtain this error:
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
how can i compare the datetimes field without the hours part
thanks
Well this is certainly not the most efficient way to do it, but you can try something like:
i.SpesaVitto = db.TDP_NotaSpeseSezB.Where(p => p.GiornoFine == null &&
(new DateTime((p.Giorno as DateTime).Year, (p.Giorno as DateTime).Month, (p.Giorno as DateTime).Day) == (new DateTime((i.Data as DateTime).Year, (i.Data as DateTime).Month, (i.Data as DateTime).Day) &&
p.MissioneID == missioneID).Sum(p => p.Costo);
Depending on the requirements I would probably implement something cleaner and faster but it would depend on how the dates are stored in your database.
Check out this question it looks like the syntax error may be in your SQL, not in your LINQ. The asker in that question had written:
SQL ------
Select
EmployeeNameColumn
From
EmployeeTable
WHERE StartDateColumn.Date <= GETDATE() //Today
SQL ------
When they should have written:
SQL ------
Select
EmployeeNameColumn
From
EmployeeTable
WHERE StartDateColumn <= GETDATE() //Today
SQL -
solution for your problem will be the "SqlFunctions class and DateDiff" http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx

FirstOrDefault behavior directly in LINQ statement

Seems like I may have missed something simple in the syntax, but I'd like to get the results of FirstOrDefault from a linq statement directly without having to store the IEnumerable in a temporary variable first. Something like this:
var bestCar = from c in cars
orderby c.Price
select first c
I know the first keyword doesn't actually exist but illustrates what I'd like to do. I also know I can wrap the from...select statement in parenthesis and call FirstOrDefault directly but I think the above syntax is cleaner and easier to read.
Enumerable.FirstOrDefault is one of the extension methods in the Enumerable class which does not have a corresponding LINQ syntax element. The only way to bind to this method is via method call syntax.
You can avoid the temporary by doing the follownig
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
There isn't a way to do that. LINQ is used for defining a query. Doing that doesn't actually cause an evaluation, whereas executing FirstOrDefault (or enumerating over it) executes the query.
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault()
OR
var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
Sorry I didn't read your question entirely, it seems that this may be exactly what you don't want to do.
In VB you can use 'Aggregate':
Dim BestCar = Aggregate c In cars
Order By c.Price
Into FirstOrDefault

Dynamic LINQ query using an Attribute

I have had some success getting the MSFT Dynamic Linq stuff to work, but now I need to create a "Where" clause that includes an Attribute.
The error I get is "No applicable aggregate method 'First' exists"
Here is my code:
where = "Element(XName.Get(\"procedure\")).Attributes(XName.Get(\"code\")).First() = \"28002\"";
var q2 = doc.Elements().Descendants("vocabularybody").AsQueryable().Where(where);
if (q2 != null && q2.Count() > 0)
foundItems.Add(item);
here is my XML
<vocabulary>
<vocabularyheader>
<vocabularyid>5</vocabularyid>
<vocabularyname>Scheduled Procedure</vocabularyname>
</vocabularyheader>
<vocabularybody>
<procedure code="28002" type="Surgery"/>
</vocabularybody>
</gazoontvocabulary>
I'm not familiar with the Dynamic LINQ library yet but shouldn't you need the equality operator (==) and not the assignment operator (=) for the where clause?

Resources