How to programmatically set label text - Linq To Entities - linq

I have to set the label text of a load of differnet labels on a web page based upon user preferences.
I have the following code that is place upon the label load event (probably wrong!)
string memberid = Session["MemberID"].ToString();
string locationid = Session["LocationID"].ToString();
string userName = Membership.GetUser().UserName;
string uuf1 = "UnitUserField1";
MyEntities lblUUF1Text = new MyEntities();
lblUUF1.Text = lblUUF1Text.tblUserPreferences
.Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
.Select(p => p.Alias)
.ToString();
However when I run this, the label text returned is:
System.Data.Objects.ObjectQuery`1[System.String]
Can someone point me in the error of my ways. I'm feeling very, very thick at the moment.

You're writing a query and then asking that query to be converted to a string. Do you only want the first result of that query? If so, it's easy:
lblUUF1.Text = lblUUF1Text.tblUserPreferences
.Where(p => p.MemberID == memberid &&
p.LocationID == locationid &&
p.Username == userName && p.ColumnName == uuf1)
.Select(p => p.Alias)
.First();
(I'm assuming that the type of p.Alias is already string, but that you included the call to ToString as an attempt to coerce the query into a string to make it compile.)
Note that if there are no results, that will blow up with an exception. Otherwise it'll take the first result. Other options are:
Sure there's exactly one result? Use Single()
Think there's either zero or one? Use SingleOrDefault(), store in a local variable and set the label text if the result isn't null.
Think there's anything from zero to many? Use FirstOrDefault() in the same way.

You need a .First() in there
lblUUF1.Text = lblUUF1Text.tblUserPreferences
.Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
.Select(p => p.Alias).First().ToString();

ToString() will return the object type as you see, what you will need to do is this:
lblUUF1.Text = lblUUF1Text.tblUserPreferences
.Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
.Select(p => p.Alias).SingleOrDefault();

Related

LINQ EF AND VS2017

I wrote a query and worked on LINQPAD
from x in FacilityData
from y in FavInformation
where y.UserID == 1 && x.ID == y.FacilityID
select new
{
xID = x.ID,
xDistrictName = (from y in _Ilcelers
where y.ID == x.DistrictID
select y.IlceAd).FirstOrDefault(),
xName = x.Name,
Value = (from o in Tags
from p in Table_tags
where o.Prefix != null && o.Prefix == p._NAME && o.Facility == y.FacilityID
orderby p.İd descending
select new
{
FType = o.TagType,
Name = o.TagsName,
Value = p._VALUE,
Time = p._TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
}
result
the result is perfect
but does not work in visual studio,
Value = (from o in DB.Tags
from p in DB.table_tags
where o.Prefix != null && o.Prefix == p.C_NAME && o.Facility == 11
orderby p.id descending
select new
{
FType=o.TagType,
Name = o.TagsName,
Value = p.C_VALUE,
Time = p.C_TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
and it gives an error.
I guess the part with .Take() doesn't work because it's linq to EF.
error:
Limit must be a DbConstantExpression or a Db Parameter Reference Expression. Parametre name: count]
error image
thank you have a good day
Not sure but I will just throw it in. If you are talking about linq to ef/sql, it is possible they dont know a thing about C#. If take() would be the problem try to get the select result local first by doing .tolist(). Afterwards use your take funtion.
.ToList().Take(Tags.Count(h => h.Facility == y.FacilityID))

Linq : How to search with 'Any' or 'All'

I have a search page where you can enter 4 search criteria. User can enter all 4 or less and when I do the search I have to look for all 4 if they are entered and if not take all for the value not entered. Example: my search parameters are FirstName, LastName, City and Zip. Now if someone enters John and Zip 01803 I need to ignore other 2 and look for all Johns in that zip code. Can I do that in one query somehow? I know I can do that if I write multiple ones to check which values are null but that looks not so tedious. I want to know if I can use 'Any' or 'All' in LINQ to do that?
if (fname == null) fname = "";
if (lname == null) lname = "";
if (city == null) city = "";
var results = from c in context.Company.Where(d => d.CompanyCode == identifikator)
join p in context.Person.Where(d => (d.FirstName.Any(??) || d.FirstName.Contains(fname)) && d.LastName.Contains(lname) && d.City.Contains(city) && d.ZIP==zip) on c.CompanyId equals p.Identifikation
join ts in context.TSSession on p.PersonId equals ts.PersonId
select new
{
firstname = p.FirstName,
lastname = p.LastName,
mail = p.EMail,
order = tp.Order,
timestamp = ts.TimeStamp,
personid = p.PersonId
};
You can build your where expression like this:
var personsSubQuery = context.Persons;
if(fname != null)
personsSubQuery = personsSubQuery.Where(x=>x.FirstName.Contains(fname));
if(lname != null)
personsSubQuery = personsSubQuery.Where(x=>x.LastName.Contains(lname));
and so on.
then in your query just use personsSubQuery in place of your context.Persons.Where.
I don't see Any or All methods to be usable in this scenario.

Non-Static method requires a target?

I have never seen this error before and its very confusing, I am essentially trying to do something where I say find me all locations (will only return one) that match the location name passed in and the type:
string name = columns[40];
Location type = db.Locations.Where(l => l.name == name).FirstOrDefault();
Location loc = db.Locations.Where(l => l.name == name && l.type == type.type).FirstOrDefault();
There's probably a better way to do what I want in one fell swoop, but essentially I get the name from a column (this comes from a csv file), and then say, get me that locations information. After this I say ok now that I have all that jazz, go get me a location with this name and its type.
But I get the error:
Non-Static method requires a target
The top level method all this code runs in is:
static void Main(string[] args){}
Essentially its just a console app. So whats going on?
db is the context class, this should be obvious.
columns is me pulling the data from the csv file, in this case columns[40] would be something like "New York"
Full Error message from the stack trace: {"Non-static method requires a target."}
Note: The question posted as a "possible answer" does not help in this case as the main method I am running this code in is static.
Upon further investigation I found the name and type were null so I did the following fix:
if (name != null)
{
Location type = db.Locations.Where(l => l.name == name).FirstOrDefault();
Location loc = db.Locations.Where(l => l.name == name && l.type == type.type).FirstOrDefault();
locationNearbyId = loc.id;
// More code
}
Alas I still get the error at: Location loc = db.Locations.Where(l => l.name == name && l.type == type.type).FirstOrDefault();
I had this happen to me today. Come to find out, I was doing this:
Player player = db.Players
.Where(p => p.ClubID == course.Club.ID && p.IsActive == true && p.Phone != null)
.ToArray()
.SingleOrDefault(p => p.Phone.FormatPhoneNumber() == phone);
where course.Club was being lazy-loaded via EF from my database. At first, I thought my problem was the FormatPhoneNumber extension, but then found that removing the course.Club.ID fixed the issue:
int clubID = course.Club.ID;
Player player = db.Players
.Where(p => p.ClubID == clubID && p.IsActive == true && p.Phone != null)
.ToArray()
.SingleOrDefault(p => p.Phone.FormatPhoneNumber() == phone);
So, avoid using values gleaned from lazy-loaded objects in subsequent LINQ queries - assign them to local variables and then use those variables in your query.
Turns out that because name and type can be null type has to be set out side the if statement and thus i must check if type and name are null before continueing:
name = collumns[40];
type = db.Locations.Where(l => l.name == name).FirstOrDefault();
if (name != null && type != null)
{
Location loc = db.Locations.Where(l => l.name == name && l.type == type.type).FirstOrDefault();
//More code....
}
It is a fact that the problem is due to the null "type" object.
I would solve this way:
var tType = type?.type;
Location loc = db.Locations.Where(l => l.name == name && (type != null && l.type == tType)).FirstOrDefault();

LINQ to Entities does not recognize the method 'Char get_Chars(Int32)' method, and this method cannot be translated into a store expression

I would like to select only the records that have the field "1" from the string eventTriggers (that looks something like this : "00100010" )
I've tried and succesfully done so with more than 1 calls .. but i doubt its efficient. Basically I would want something like this ... but apprently LINQ does not support this.
(LINQ to Entities does not recognize the method 'Char get_Chars(Int32)' method, and this method cannot be translated into a store expression.)
using (var service = new dB.Business.Service.BaseBusinessService<memo>())
{
List<memo> result = service.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers[index] == '1').ToList();
}
Any hints towards the correct solution ? Thank you !
I Had the same problem and solved It with substring.
ervice.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers.Substring(index,1) == "1").ToList();
EF can't convert the char array operation into a valid query. How about
IEnumerable<Memo> memos
using (var service = new dB.Business.Service.BaseBusinessService<Memo>())
{
memos = service.Repository.GetQuery()
.Where(p => p.ID == ID).AsEnumerable();
}
var result = memos.Where(m => m.eventTriggers[index] == '1').ToList();
This gets all the memos with a matching ID locally then filters on the eventTriggers array.
Alternatively you could convert eventTriggers into a numeric value and use a bit mask, this would probably be a much faster query.
Linq looking like this,
using (var service = new dB.Business.Service.BaseBusinessService<Memo>())
{
result = service.Repository.GetQuery()
.Where(p =>
p.ID == ID
&&
m.eventTriggers & mask != 0).ToList();
}
more exapmles here
Solved:
using (var service = new dB.Business.Service.BaseBusinessService<memo>())
{
List<memo> result = service.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers.Contains('1')).ToList();
}

How do I set conditions from multiple tables in my LINQ query?

In the query below, I want to return people that meet multiple conditions. Some of the conditions apply to fields in the table containing the people to be returned. The other condition is applied to a different table (EmailAddresses) linked to the main table (People) via PersonId.
var t = People.Where(x =>
x.Type == 102 &&
x.FirstName == "Bob" &&
x.LastName == "Williams" &&
x.EmailAddresses.Where (ea=> ea.EmailAddress
== "bob.williams#acme.org")
)
.Select(x => x.PersonId)
How do I do this?
Do understand this right, at least one of them should have that adress? If yes, use the Any method:
var t = People.Where(x =>
x.Type == 102 &&
x.FirstName == "Bob" &&
x.LastName == "Williams" &&
x.EmailAddresses.Any(ea=> ea.EmailAddress
== "bob.williams#acme.org")
)
.Select(x => x.PersonId)
Any returns true if at least one of the elements of the IQueryable<T> fulfills the predicate.
I think you could do it with a join, something like this...
var t = from p in People
join e in EmailAddress on p.PersonId equals e.PersonId into pe
from a in pe.DefaultIfEmpty
where p.Type == 102 &&
p.FirstName == "Bob" &&
p.LastName == "Williams" &&
a.EmailAddress == "bob.williams#acme.org"
select p.PersonId

Resources