ToString() method not supported - c#

I am trying to create a selectlist in c#. My code :
var ceremonies = db.Ceremonies;
var Ceremonies =
from c in ceremonies
select new SelectListItem
{
Text = c.Name + "_" + c.Date,
Value = c.Id.ToString()
};
But here i am getting exception something like ToString() method not supported. Whats the problem ?

Your query is being transformed into SQL - but the call to ToString can't be handled properly. Generally the simplest way of fixing this is to effectively split the query into the part that needs to be done in the database, then switch to LINQ to Objects via AsEnumerable:
var ceremonies = db.Ceremonies
.Select(c => new { c.Name, c.Date, c.Id }
.AsEnumerable()
.Select(c => new SelectListItem {
Text = c.Name + "_" + c.Date,
Value = c.Id.ToString()
});
As an aside, declaring two local variables which vary only by case gives pretty nasty readability.

Related

OrderBy does not work when sort a list and Resharper also displays a warning "return value of pure method not used"

I have consulted Warning in Resharper "Return value of pure method is not used" post but have not found the solution
Take a look at my code
var listDetail = (from p in Expense.GetAll()
where p.Group == "001"
select new ExpenseViewModel()
{
ExpenseC = p.ExpenseC,
Group = p.Group,
Cost = p.Cost,
}).ToList();
listDetail.OrderBy(p => p.ContainerSizeI); //warning displayed at OrderBy with content "return value of pure method not used"
As a result, the listDetail variable is not sorted in ascending order as I want
You need to move the OrderBy into your method chain.
var listDetail = (from p in Expense.GetAll()
where p.Group == "001"
select new ExpenseViewModel()
{
ExpenseC = p.ExpenseC,
Group = p.Group,
Cost = p.Cost,
})
.OrderBy(p => p.ContainerSizeI)
.ToList();

Linq query Contains method with where condition with case sensitive less search

I am trying get the data which is contains single word with in the word.Like below query.
List<Models.tbluser> memberslist = new List<Models.tbluser>();
var obct = (from memlist in objcontext.tblusers
where memlist.logname.Contains(member)
select new
{
userid = memlist.userid,
logname = memlist.logname,
decription = memlist.description
}).ToList();
foreach (var item in obct)
{
memberslist.Add(new tbluser
{
userid = item.userid,
logname = item.logname,
description = item.decription
});
}
return Json(memberslist);
But here my problem is i need to search with out case sensitive.
For example
If i search with 'a' i need to get data like Admin,Administrator,User Data.
But i am not getting all these because i am searching with Contains() method.Please let me know how can i get all value either the search value is case sensitive less also.
Change your where condition to be:
memlist.logname.ToUpper().Contains(member.ToUpper())
As a side note, you can shorten your query a bit (you don't need to create an intermediary list):
var memberslist = objcontext.tblusers
.Where(x => x.logname.ToUpper().Contains(member.ToUpper())
.AsEnumerable()
.Select(x => new tbluser
{
userid = x.userid,
logname = x.logname,
decription = x.description
})
.ToList();
return Json(memberslist);
You can change them to Lower or Upper Case when checking the condition using ToLower() or ToUpper():
var obct = (from memlist in objcontext.tblusers
where memlist.logname.ToLower().Contains(member.ToLower())
select new
{
userid = memlist.userid,
logname = memlist.logname,
decription = memlist.description
}).ToList();

Can't Concatenate String in LINQ query

I am just trying to concatenate a string on to a column returned from the database like so:
var aaData =
(from pr in ctx.PaymentRates
where pr.ServiceRateCodeId == new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96")
select new
{
Id = pr.Id,
Rate = pr.YearOneRate + "helloWorld"
})
.ToList();
It gives me this error:
Unable to cast the type 'System.Nullable`1' to type 'System.Object'.
LINQ to Entities only supports casting EDM primitive or enumeration
types.
So, then I tried this:
var aaData =
(from pr in ctx.PaymentRates
where pr.ServiceRateCodeId == new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96")
select new
{
pr = pr
})
.AsEnumerable()
.Select(x => new
{
Id = x.pr.Id,
Rate = x.pr.YearOneRate + "helloWorld"
})
.ToList();
But, now it gives me this error:
Object reference not set to an instance of an object.
On this line:
.Select(x => new
How can I concatenate these strings in LINQ?
The quick solution
Regarding your second code chunk I need to point out to you that you're actually doing two left outer joins on the Countries table/set, one for homeC and one for hostC.
That means that you are willing to accept null values for those two variables.
In other words, since they can be null you are somehow allowing this right here to crash with NullReferenceException, should those variables turn out to be null:
.Select(x => new
{
Id = x.pr.Id,
HomeCountry = x.homeC.Name,
HostCountry = x.hostC.Name,
Rate = x.pr.YearOneRate + "helloWorld"
})
The error (NullReferenceException or as you saw it's message: "Object reference not set to an instance of an object.") is not here
.Select(x =>
but rather here
x.homeC.Name and x.hostC.Name
where you will most certainly dereference a null reference.
That's just Visual Studio's way of pointing out the best statement that fits around the error.
So, the quickest solution would be to do this:
.Select(x => new
{
Id = x.pr.Id,
HomeCountry = (x.homeC != null) ? x.homeC.Name : "HomeCountry not found",
HostCountry = (x.hostC.Name != null) ? x.hostC.Name : "HostCountry not found",
Rate = x.pr.YearOneRate + "helloWorld"
})
Notice the modification which ensures that you will still be able to extract some information from result set records for which homeC and hostC are null.
EDIT
Regarding the first query you posted:
var aaData =
(from pr in ctx.PaymentRates
where pr.ServiceRateCodeId == new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96")
select new
{
Id = pr.Id,
Rate = pr.YearOneRate + "helloWorld"
})
.ToList();
my guess is that your 'YearOnRate' property is of type 'Nullable< of something >" (maybe decimal -- so for instance it is maybe a decimal? YearOnRate { get; set; }) and the corresponding column in the database is a nullable one.
If that is the case, then I think (in this first version of your endeavour) you could try to do this:
Rate = (pr.YearOnRate != null) ? pr.YearOneRate.Value + "helloWorld" : "[null]helloWorld"
and get away with it.
My guess is that either x.homeC, x.hostC, or x.pr are null. If you're fine using AsEnumerable to convert to Linq-to-Objects then you could just change your projection to
.Select(x => new
{
Id = (x.pr.HasValue ? x.pr.Id : 0),
HomeCountry = (x.homeC.HasValue ? x.homeC.Name : null),
HostCountry = (x.hostC.HasValue ? x.hostC.Name : null),
Rate = (x.pr.HasValue ? x.pr.YearOneRate : null) + "helloWorld"
})
My problem was, I wasn't using .AsEnumerable() properly. The code below works:
var aaData =
(from pr in ctx.PaymentRates
from homeC in ctx.Countries.Where(x => x.Id == pr.HomeCountryId).DefaultIfEmpty()
from hostC in ctx.Countries.Where(x => x.Id == pr.HostCountryId).DefaultIfEmpty()
from curr in ctx.Currencies.Where(x => x.Id == pr.YearOneCurrencyId).DefaultIfEmpty()
where pr.ServiceRateCodeId.Value.Equals(new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96"))
select new { pr, homeC, hostC, curr })
.AsEnumerable()
.Select(x => new
{
Id = (string)(x.pr.Id.ToString() + "test"),
HomeCountry = (x.homeC != null ? x.homeC.Name : ""),
HostCountry = (x.hostC != null ? x.hostC.Name : ""),
Rate = (x.pr.YearOneRate ?? 0) + " (" + x.curr.Code + ")"
})
.ToList();
You have used DefaultIfEmpty on both homeC and hostC so you can get a null reference when you call homeC.Name or hostC.Name
Try using HomeCountry = homeC == null ? null : homeC.Name instead
If pr.YearOneRate is not a string and you want the concatenation done by the database engine you need to tell Linq-to-Entities to generate sql to convert it. If you are using Sql Server you can use this:
SqlFunctions.StringConvert(pr.YearOneRate) + "helloWorld"
If you don't need the concatenation done in the database then you can use AsEnumerable() before the Select so that you are running Linq-To-Objects

Trim string in LINQ C#

I like to trim following string but there is an error:
var getClients = (from c in GeneralUtillities)
orderby c.Client_Name
select new
{
c.Client_Name.Trim(),
c.Client_Code,
});
Thnx
You need to provide names for the Anonymous type object properties
var getClients = (from c in GeneralUtillities)
orderby c.Client_Name
select new
{
Name = c.Client_Name.Trim(),
Client_Code = c.Client_Code
};
If you don't provide a name in an anonymous type property, it attempts to use the property name of the value it's being assigned. As you've invoked a method on the property, it can't resolve the name. You need to specify it:
var getClients = (from c in GeneralUtillities)
orderby c.Client_Name
select new
{
Client_Name = c.Client_Name.Trim(),
c.Client_Code,
});
I see 3 things - since you didn't specify the error I'm not certain what the true problem is, but here are some guesses:
You've got a closing paren at the end of GeneralUtillities which is a syntax error
You don't specify a name for the first field in the anonymous type
Linq-to-Entities may not support the use of Trim
Here's an alternative:
var getClients = (from c in GeneralUtillities
orderby c.Client_Name)
.AsEnumerable()
.Select (c => new
{
Client_Name = c.Client_Name.Trim(),
Client_Code = c.Client_Code, // for readability, not necessary
});
The name of the property of an anonymous type must be known at compile time.
var getClients = (from c in GeneralUtillities)
orderby c.Client_Name
select new
{
Name= c.Client_Name.Trim(),
Code = c.Client_Code,
});
var getClients =
(from c in GeneralUtillities.a.data
orderby c.Client_Name
select new
{
c.ID_Client,
c.Client_Name,
});
This is right code, so the problem is to trim Client Name to have no space in start and end.

Concatenating two fields in LINQ select

I have a dropdownlist, ddCourse, that I'm populating with the following LINQ query:
var db = new DataClasses1DataContext();
ddCourse.DisplayMember = "COURSE_TITLE";
ddCourse.ValueMember = "COURSE_ID";
ddCourse.DataSource = db.COURSE_MASTERs.OrderBy(c => c.COURSE_TITLE)
.Select(c => new { c.COURSE_ID, c.COURSE_TITLE })
.ToList();
There's another field, though, that I'd like to concatenate to the COURSE_TITLE field in my selection. So, I'd like my selection to look like:
.Select( c => new {c.COURSE_ID, c.CIN + " " + c.COURSE_TITLE})
The only problem is that this, apparently, isn't how it's done. I'm basically wanting to join c.CIN with c.COURSE_TITLE (and have a space in the middle). Can someone offer me some pointers on how to accomplish this?
The reason I want to do this is that, right now, the only thing appearing in the dropdownlist is the course title. I'd like to have the course ID number (CIN) concatenated to it when it displays.
EDIT: For clarification, I'm using Linq-to-SQL.
use this
.Select( c => new {c.COURSE_ID, COURSE_TITLE =string.Format("{0} {1}" ,c.CIN ,c.COURSE_TITLE)})
You need to name your anonymous members:
.Select( c => new {COURSE_ID = c.COURSE_ID, COURSE_TITLE = c.CIN + " " + c.COURSE_TITLE})
Write your Select like this:
.Select( c => new {c.COURSE_ID, COURSE_TITLE = c.CIN + " " + c.COURSE_TITLE})
Anonymous types need to have their column names specified, in case they cannot be inferred.
For c.COURSE_ID C# is smart enough to generate a member called COURSE_ID in the anonymous type. For the expression c.CIN + " " + c.COURSE_TITLE it cannot.

Categories