Linq to datasets - getting specific column value in C# - linq

i'm trying to get an error description according to error Id:
String errorDesc = from resultCodesTableRow in resultCodesDT.AsEnumerable()
where resultCodesTableRow.Field<int>("Error_Code_Column_Name") == errorCode
select resultCodesTableRow.Field<string>("Error_Desc_Column_Name").ToString();
why do i get the error:
"Cannot implicitly convert type 'System.Data.EnumerableRowCollection' to 'string'" ?
how does the query supposed to look ?

Change
resultCodesDT.AsEnumerable() to resultCodesDT.rows
Does this work:
where (int)resultCodesTableRow.GetItem("Error_Code_Column_Name") == errorCode
select resultCodesTableRow.GetItem("Error_Desc_Column_Name")

I am not pretty sure what the actual LINQ query is returning most probably by seeing it and as you said you are getting error it might be returning a Collection so in order to avoid use first or last method to the query ie
String errorDesc = from resultCodesTableRow in resultCodesDT.AsEnumerable()
where resultCodesTableRow.Field("Error_Code_Column_Name") == errorCode
select resultCodesTableRow.Field("Error_Desc_Column_Name").First().ToString();

the Select function in your statement will return an IEnumerable.
instead you need to use something like
String errorDesc = (from resultCodesTableRow in resultCodesDT.AsEnumerable()
where resultCodesTableRow.Field<int>("Error_Code_Column_Name") == errorCode
select resultCodesTableRow.Field<string>("Error_Desc_Column_Name").ToString()).First();
or maybe this would work but is untested
String errorDesc = resultCodesDT.Where(X=> x.Error_Code_Column_Name==errorCode)
.Select(s=>s.Error_Desc_Column_Name.toString()).First();

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.

Postgres datatype conversion differ on Ubuntu and windows

I am getting following exception on windows while running the below
ERROR: operator does not exist: numeric = character varying Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts." while executing with query parameter
I am passing the Numeric String for parameter using function as a named parameter to the query
getUIDCount(String id) {
...
select count(UID) as icrd FROM UID_tbl WHERE id = ?
...
}
where id is numeric(5,0)" in table
Everything works well on Ubuntu but getting Error while running the same code on windows. I have to do the explicit casting just for windows. I am using PostgreSQL 9.4.3. I am using "org.hibernate.dialect.PostgreSQLDialec" and grails 2.3.11 with runtime 'org.postgresql:postgresql:9.3-1100-jdbc41'
updated with how it is getting called
def Integer getUIDSetSize(String _id)
{
Integer i = 0;
Sql sql = new Sql(dataSource);
String sqlt = """select count(UID) as icrd FROM UID_tbl WHERE _id = ?""";
log.trace(sqlt);
sql.eachRow(sqlt, [_id], { row -> i = row.icrd; });
return i;
}
This how it get called def _id1 = params._id1; count1 = HelperService.getUIDSetSize(_id1)
The workaround for casting from varchar to numeric is
CREATE CAST(VARCHAR AS NUMERIC) WITH INOUT AS IMPLICIT;
This is not the best solution and would suggest selective casting from the code.

Linq query returns null. Can't figure out why

My result returns null.
IEnumerable<DataRow> result = ( from r in db.vedhaeftedeFilers.AsEnumerable() where r.beskedId == id select new { r.filnavn, r.filtype, r.data })as IEnumerable<DataRow>;
there are data in the database, and the id are correct. I am guessing that it has
something to do with my use of IEnumerable, but cant figure out what the problem is.
The as operator will return null if the object you are passing is not actually an IEnumerable<DataRow>, which it obviously is not because you are projecting into an anonymous type with select new { ... }.
As an aside, the AsEnumerable() call will ruin your performance by making your database table behave like a dumb array.
What exactly are you trying to do here?
select new { r.filnavn, r.filtype, r.data }
That creates an anonymous type with read only properties filnavn, filtype and data. Thus the type of the LINQ comprehension expression (from ... select) is IEnumerable<anonymous>.
This type does not implement IEnumerable<DataRow>, so as Jon notes, it will return null.
When you do this:
select new { r.filnavn, r.filtype, r.data }
...you are returning a collection of an anonymous type. This is a problem because you're trying to cast this collection to IEnumerable<DataRow>. Since you're using as to cast, it's "dying silently" and returning null since casting with the as keyword doesn't throw an InvalidCastException if the cast fails (as opposed to casting with parethesis like MyClass x = (MyClass)MyObj).
Try this instead:
var result = ( from r in db.vedhaeftedeFilers.AsEnumerable() where r.beskedId == id select new { r.filnavn, r.filtype, r.data });
Notice I used var and didn't attempt to cast the result to a type.

TargetInvocationException thrown when attempting FirstOrDefault on IEnumerable

I suspect I'm missing something rather basic, yet I can't figure this one out.
I'm running a simple linq query -
var result = from UserLine u in context.Users
where u.PartitionKey == provider.Value && u.RowKey == id.Value
select u;
UserLine user = null;
try
{
user = result.FirstOrDefault();
}
For some reason this produces a TargetInvocationException with an inner exception of NullReferenceException.
This happens when the linq query produces no results, but I was under the impression that FirstOrDefault would return Default<T> rather than throw an exception?
I don't know if it matters, but the UserLine class inherits from Microsoft.WindowsAzure.StorageClient.TableServiceEntity
there are two possible reasons:
provider.Value
id.Value
Are you sure that theese nullables have value. You might want to check HasValue before
var result = from UserLine u in context.Users
where (provider.HasValue && u.PartitionKey == provider.Value)
&& (id.HasValue && u.RowKey == id.Value)
select u;
UserLine user = null;
try
{
user = result.FirstOrDefault();
}
I thought it produced a different error, but based on the situation in which the problem is occurring you might want to look to check if context.IgnoreResourceNotFoundException is set to false? If it is try setting it to true.
This property is a flag to indicate whether you want the storage library to throw and error when you use both PartitionKey and RowKey in a query and no result is found (it makes sense when you think about what the underlying REST API is doing, but it's a little confusing when you're using LINQ)
I figured it out - the problem occured when either id or provider had '/' in the value, which the id did. when I removed it the code ran fine
Understanding the Table Service Data Model has a section on 'Characters Disallowed in Key Fields' -
The following characters are not allowed in values for the
PartitionKey and RowKey properties:
The forward slash (/) character
The backslash () character
The number sign (#) character
The question mark (?) character
Here's some fun try putting the where query the other way around like this to see if it works (I heard a while ago it does!):
where (id.HasValue && u.RowKey == id.Value) && (provider.HasValue && u.PartitionKey == provider.Value)
Other than this you can now set IgnoreResourceNotFoundException = true in the TableServiceContext to receive null when an entity is not found instead of the error.
It's a crazy Azure storage thing.

nhibernate.linq simple (read dumb) question

I'm trying to wrap my head around linq -> nhib
I have a simple bit of sql that i'm trying to get working in nhibernate.linq
select * from
ColModel where ColModel.DataIndex
not in ('CostElement1', 'CostElement2', 'CostElement3')
and ColModel.ReportId = 1
The list of excluded DataIndex values comes in in the form of a List<string> called excludeNames
Here is what I have tried but it seems that it's not really feeling the love:
var s = base._sessionManager.OpenSession();
var query = from col in s.Linq<ColModel>()
where col.Report.Id == reportid &&
!(from c in s.Linq<ColModel>() select c.DataIndex).Contains(excludeNames)
select col;
return query.ToList();
the error:
The type arguments for method 'System.Linq.Enumerable.Contains<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
I'm pretty sure I'm borfing this from the offset so any pointers would be well appreciated :)
w://
Contains doesn't accept a list.
There are ways to work around this in LINQ, but I'm not sure which, if any, of those will work in NH Linq
I think you have your exclusion backwards.
s = base._sessionManager.OpenSession();
var query = from col in s.Linq<ColModel>()
where col.Report.Id == reportid &&
!excludeNames.Contains(col.DataIndex)
select col;
return query.ToList();
Collection.Contains(item) will produce the SQL item in (...collection...), adding the negation will get you what you want.

Resources