For the following code
var validate = from P in this.DataContext.Persons
where P.UserName.Equals(login) && P.Password.Equals(password)
select new
{
P.FirstName,
P.LastName,
P.EmailAddress
};
If record exists i want to get the first name and return it. How can i get the firstName from var validate?
validate here is going to be a set (IQueryable<T>) of data. You may need to use FirstOrDefault(), for example:
var record = validate.FirstOrDefault();
if(record != null) {
string firstName = record.FirstName;
}
Console.WriteLine(validate.FirstOrDefault().FirstName);
Otherwise you'll have to loop through the set since that what your query is returning Likely a set of one but it's still a set.
Try the following:
var validate = (from P in this.DataContext.Persons
where P.UserName.Equals(login) && P.Password.Equals(password)
select new
{
P.FirstName,
P.LastName,
P.EmailAddress
}).FirstOrDefault();
if (validate != null)
{
var firstName = validate.FirstName;
...
}
Related
I have to return only the primary contact within an account of a person that is a member, but my query is returning all all members within the organization. I have tried reordering it and using stuff like Single() but with no luck. I need a way to put a where clause that says I only want the Primary Contact with an account.
if ((!string.IsNullOrEmpty(organization)) && (!string.IsNullOrEmpty(city)) && state != null)
{
var corporatemembers = (from a in crmContext.bpt_membertypeSet
where a.bpt_membertypename == "Member (Individual)" || a.bpt_membertypename == "Courtesy"
|| a.bpt_membertypename == "Affiliate" || a.bpt_membertypename == "Member"
select new { a.Id }).ToList();
foreach (var corporatemember in corporatemembers)
{
var directories = (from b in crmContext.AccountSet
join a in crmContext.ContactSet
on b.Id equals a.ParentCustomerId.Id
where a.bpt_MemberTypeId.Id == corporatemember.Id
where a.bpt_memberstatus == (int)bpt_memberstatus.Active
where b.Name.Contains(organization)
where a.Address1_City.Contains(city)
where a.bpt_stateorusterritory.Value == state.Value
select new { b.PrimaryContactId, b.EMailAddress1, a.Address1_City, b.Name, b.WebSiteURL, a.bpt_stateorusterritory }).ToList();
foreach (var directory in directories.ToList().OrderBy(o => o.Name))
{
var cityState = String.Empty;
if (directory.bpt_stateorusterritory != null)
cityState = directory.Address1_City + ", " + Utility.GetOptionSetValueLabel(crmContext, new Microsoft.Xrm.Sdk.Entity(Xrm.Contact.EntityLogicalName), "bpt_stateorusterritory", new Microsoft.Xrm.Sdk.OptionSetValue(directory.bpt_stateorusterritory.Value));
else
cityState = directory.Address1_City;
oMemberList.Add(new Members { FullName = directory.PrimaryContactId, FullNameEmail = directory.EMailAddress1, OrganizationName = directory.Name, OrganizationUrl = directory.WebSiteURL, CityState = cityState });
}
}
}
this code returns all if the search categories are all filled. I have 4 clauses for all scenarios. But at the end of the whole thing I have:
oMembers.ToList()
Thanks
Edit: here is sample data but the output is wrong. There should only be one organization and one contact
I think you are using the wrong field for the join here. This would return all contacts who are a child of that account - which is probably why you are getting multiple results.
on b.Id equals a.ParentCustomerId.Id
The primary contact field on the account is primarycontactid so I suggest you update your query to reference that attribute instead.
I have a LINQ query, I need to return all the customers in our database, however not all of them have a middle name. This is my query:
select new
{
firstName = a.firstname,
middleName = a.middlename,
lastName = a.lastname,
};
foreach(var c in queryAccount)
{
console.writeline(c.firstname);
console.writeline(c.middlename);
console.writeline(c.lastname);
}
What I am looking for is something similar to:
if (c.middlename != null)
{
console.writeline(c.middlename);
}
Does anyone know how I could get this to work?
You can simply use Null Colaescing operator:-
select new {
firstName = a.firstname,
middleName = a.middlename ?? String.Empty,
lastName = a.lastname,
};
Rahul's answer is correct. Additionally in case you don't want to assign 'middleName' at all you can do:
Select(x =>
{
var obj = new TestData
{
Lastname = x.Lastname,
Firstname = x.Firstname
};
if (!string.IsNullOrEmpty(x.Middlename))
obj.Middlename = x.Middlename;
return obj;
});
I am trying to do something like the following:
I am not sure how to initialize teh restultCLList as I cannot set it to null.
var resultCLlist = null;
if (RdoStatus.SelectedValue == "Incomplete")
{
resultCLList = (from ms in db.ver_ServiceReport
join gc in db.map_Sit
on ms.SiteId equals gc.SiteID
where gc.CompanyId == companyId
select new ServiceReport
{
VerificationId = ms.VerificationId,
SiteId = ms.SiteId,
}
).ToList();
}
else
{
resultCLList = (from ms in db.ver_ServiceReport
join gc in db.map_Sites
on ms.SiteId equals gc.SiteID
where gc.CompanyId == companyId
select new ServiceReport
{
VerificationId = ms.VerificationId,
SiteId = ms.SiteId,
SiteName = gc.SiteName,
TimeStamp = ms.TimeStamp,
EntryDate = ms.EntryDate,
Supplier = ms.Supplier
}
).ToList();
}
Why don't you use List<ServiceReport> instead of var ?
You can't initialize var to a null value, because null is not a type itself.You can cast it to object but it won't be safe.var is useful if you don't know the returning type of the expression on the right side, or if the type name is too long.In this case you know the type, so simply don't use var.
I have a LINQ query where I'm trying to return data from 2 tables, but the tables that I join are conditional.
This is what I'd like to do:
if (teamType == "A"){
var query = from foo in context.People
join foo2 in context.PeopleExtendedInfoA
select foo;
}
else {
var query = from foo in context.People
join foo2 in context.PeopleExtendedInfoB
select foo;
}
Then later on I'm filtering the query down even further. I obviously can't set it up this way because I won't be able to access "query" outside the if block, but it shows what I'm trying to do. This is an example of what I'm trying to do later on with the query:
if (state != null)
{
query = query.Where(p => p.State == state);
}
if (query != null) {
var queryFinal = from foo in query
select new PeopleGrid()
{
Name = foo.Name,
Address = foo.Address,
Hobby = foo2.Hobby
}
}
What I'm trying to return is all the data from table foo and then one field from the joined table, but depending on the logic, the joined table will differ. Both PeopleExtendedInfoA and PeopleExtendedInfoB both have the columb 'Hobby', but I have no way to access 'Hobby' from the joined table and that's the only field I need from the joined table.
How would I go about doing this?
Does PeopleExtendedInfoA and PeopleExtendedInfoB inherits from the same base class? You could create a IQueryable<BaseClass> and let the linq provider solve it for you when you add the join. For sample:
IQueryable<BasePeople> basePeople;
if (teamType == "A")
basePeople = context.PeopleExtendedInfoA;
else
basePeople = context.PeopleExtendedInfoB;
var query = from foo in context.People
join foo2 in basePeople on foo.Id equals foo2.PeopleId
select new PeopleGrid()
{
Name = foo.Name,
Address = foo.Address,
Hobby = foo2.Hobby
};
try like this:
var queryFinal = from foo in query
where foo.State == state !=null ? state : foo.State
select new PeopleGrid()
{
Name = foo.Name,
Address = foo.Address,
Hobby = foo2.Hobby
}
You can query into an intermediate type that holds the relevant fields, or if the query is simple enough you can use anonymous types as seen below. The important part is that the Join calls both have the same return types ({ p.Name, a.Hobby } and { p.Name, b.Hobby } will both be the same anon type).
var baseQuery = context.People;
var joined = type == "A" ?
baseQuery.Join(PeopleExtendedInfoA,
p => p.Id,
a => a.PeopleId,
(p, a) => new { p, a.Hobby }) :
baseQuery.Join(PeopleExtendedInfoB,
p => p.Id,
b => b.PeopleId,
(p, b) => new { p, b.Hobby });
var result = joined.Select(x => new
{
x.p.Name,
x.p.Address,
// etc.
x.Hobby
};
I figured it out. Thanks everyone for all the replies, it got my brain working again and gave me some new ideas (even though I didn't directly take any of them) I realize I needed to do the join at the very end instead of the beginning that way I don't have to deal with filtering on different types. This is what I did:
var query = from foo in context.People
select foo;
if (state != null)
{
query = query.Where(p => p.State == state);
}
if (query != null) {
if (teamType == "A")
{
var queryFinal = from foo in query
join foo2 in context.PeopleExtendedInfoA
select new PeopleGrid()
{
Name = foo.Name,
Address = foo.Address,
Hobby = foo2.Hobby
}
}
else
{
var queryFinal = from foo in query
join foo2 in context.PeopleExtendedInfoB
select new PeopleGrid()
{
Name = foo.Name,
Address = foo.Address,
Hobby = foo2.Hobby
}
}
}
I have the following two lines of code which first returns an item from a query and then creates another item with the values of the first query. i would like to combine these two lines into one statement. Keep in mind that the result of the first query might be null on some occasions.
var x = uow.Profiles.FindByID(profileId).Competitor;
return Json(new Organisation() { Name = x.Name, ID = x.ID, IsClient = x.IsClient, IsDeleted = x.IsDeleted }, JsonRequestBehavior.AllowGet);
Maybe you can add a null check if this is your concern:
var result = uow.Profiles.FindByID(profileId);
if(result != null)
{
var competitor = result.Competitor;
return Json(new Organisation() { Name = competitor.Name, ID = competitor.ID, IsClient = competitor.IsClient, IsDeleted = competitor.IsDeleted }, JsonRequestBehavior.AllowGet);
}
return null; // or whatever you can default to
Not sure exactly what the problem is and how LINQ could help (you don't necessary have to use it), just make sure your code is readable.
Edit: finally using IEnumerable (I assume Profiles is one)
ouw.Profiles.Single(p => p.Id == profileId).Select
(p => Json(
new Organisation()
{
Name = p.Competitor.Name,
ID = p.Competitor.ID,
IsClient = p.Competitor.IsClient,
IsDeleted = p.Competitor.IsDeleted
},
JsonRequestBehavior.AllowGet)
);