Hello my question is I have 2 table one is User table the other one is CustomerUsers I select them by Deleted=0 When I try to list all users and have customerId, I am having issue that sequence contains no matching element error
My Code is below any help would be appriciate
Thank you
My Dapper query is below :
public List<User> GetAllUsers()
{
List<User> user = new List<User>();
try
{
//var sql = #"SELECT * FROM [User] WHERE Deleted=0";
var sql = #"SELECT * from [User] u LEFT JOIN [CustomerUser] cu ON u.UserId = cu.CustomerUserId WHERE u.Deleted=0";
var lookUp = new List<User>();
using (var cn = Settings.Helper.ConnectionStringBiz())
{
cn.Open();
cn.Query<User,Customer,User>(sql,(u,c)=>
{
var myUser = lookUp.First(m => m.UserId == u.UserId);
if (myUser == null)
{
lookUp.Add(u);
myUser = u;
}
myUser.Customer = c;
return null;
},splitOn:"CustomerId");
}
return lookUp;
}
catch (Exception ex)
{
return user;
}
}
Issue generally occurs if your lookUp.First(m => m.UserId == u.UserId) didnt return any results.
You can use FirstOrDefault something like below instead of First which returns null (default value) if it didnt find any results for matching criteria.
var myUser = lookUp.FirstOrDefault(m => m.UserId == u.UserId);
Not sure why you are checking against lookUp, Its a new list that you created just before connecting to DB. It will always be empty (If I am not understanding it wrong).
Related
I have select2 list with employees which admin will add to project.
I select multiple employees and sending json with employee ID's to controller where
trying to get employee by employee, from company database emp list by stored procedure [Employee] to web emp db.
I face such problem that reader reads only first and last rows and skips all employees in midle
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EmpAdd()
{
var project_id = Convert.ToInt32(Request["project"]);
var company = Request["company"];
var emp = Request["emp"];
var ids = emp.Split(',');
var project = db.apsk_project.Where(x => x.id == project_id).FirstOrDefault();
cmd.CommandText = "Employee";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
foreach(var i in ids) {
var it = Convert.ToInt32(i);
var kortele = db.apsk_workers.Where(x => x.id == it).FirstOrDefault();
if(kortele == null) {
sqlConnection1.Open();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("company", company);
cmd.Parameters.AddWithValue("nr", it);
reader = cmd.ExecuteReader();
if(reader.HasRows) {
while(reader.Read()) {
apsk_workers apsk = new apsk_workers();
var v = reader.GetString(1);
var p = reader.GetString(2);
var d = reader.GetDateTime(3);
apsk.kof_id = 0;
apsk.algos_tipas = "";
apsk.vardas = v;
apsk.pavarde = p;
apsk.ar_dirba = d;
apsk.company = company;
apsk.manager = User.Identity.Name;
apsk.id = it;
db.apsk_workers.Add(apsk);
db.SaveChanges();
}
}
sqlConnection1.Close();
apsk_assigned _Assigned = new apsk_assigned();
_Assigned.project_id = project_id;
_Assigned.project = project.project;
_Assigned.worker_id = it;
db.apsk_assigned.Add(_Assigned);
db.SaveChanges();
} else {
var ar_projekte = db.apsk_assigned.Where(x => x.project_id == project_id && x.worker_id == it).FirstOrDefault();
if(ar_projekte == null) {
apsk_assigned _Assigned = new apsk_assigned();
_Assigned.project_id = project_id;
_Assigned.project = project.project;
_Assigned.worker_id = it;
db.apsk_assigned.Add(_Assigned);
db.SaveChanges();
}
}
}
Assigning person to project works fine.
I'd make several changes:
You are mixing EF with ado.net So please remove all connection opening and closings. Also lines with Parameters etc.
Since id's is a string, you can convert it to an List of ints: https://stackoverflow.com/a/9301290/169714
With Linq you can assign the employees who are already known to the project
With Linq you can foreach add the unknown employees and savechanges after adding them alll.
Let us know if you need help with specific Linq queries.
For instance: instead of db.apsk_project.Where(x => x.id == project_id).FirstOrDefault(); you could use db.apsk_project.FirstOrDefault(x => x.id == project_id);
So do not do a foreach and then a first or default to change per row, but think in collections so you can eliminate the loop and increase performance. Hope this helps. If not, please comment so I can try to explain more.
I have this query and I want to return a single value which is the I.Id and I have a parameter which is filled with an Id that is sent from a Controller to the Dao(Where the Linq query is nested).
The problem is, that this query isn't just returning a value, is returning every fields in the table that this query produces and I just want the Id.
This is the query:
public InscriptionDetail GetInscriptionIdByPersonId(int id)
{
using (var db = new HIQTrainingEntities())
{
var inscription =
from i in db.Inscriptions
join c in db.Certifications on i.PersonId equals c.PersonId
where i.PersonId == id
select new InscriptionDetail
{
Id = i.Id,
};
return inscription.FirstOrDefault();
}
}
Can someone help me with this query ?
What's wrong ?
Your return type is of InscriptionDetail. If it is only the int id you need to return, why not change to the following?
public int GetInscriptionIdByPersonId(int personId)
{
using (var db = new HIQTrainingEntities())
{
var inscription =
from i in db.Inscriptions
join c in db.Certifications on i.PersonId equals c.PersonId
where i.PersonId == personId
select i.Id;
return inscription.FirstOrDefault();
}
}
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 the following code, I'm returning results that are associated with the userId, I then want to loop through the results and build a collection and return it back to the UI.
public List<UserEmails> LoadUsersInbox(Int64 userId, int status)
{
List<UserEmails> userEmails = null;
using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
{
var emails = sqlCon.Query<UserEmailEntity>(#"SELECT e.EmailId, e.ItemId, u.Username as FromUserName, e.EmailReceived
FROM User_Emails e
INNER JOIN User_Profile u on e.FromUserId = u.UserId
WHERE ToUserId = #userId and EmailStatus = #Status",
new { ToUserId = userId, Status = status }).OrderBy(d => d.EmailReceived);
foreach (var item in emails)
{
// loop through and build and List of UserEmails
}
}
return userEmails;
}
But I can't figure out the syntax for it, can some one help me please.
You can transform the list without going to the foreach loop. You do this with the Select statement. I am not able to verify this (thus untested code), but it ought to work if you make do this:
public List<Int64> LoadUsersInbox(Int64 userId, int status)
{
using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
{
return sqlCon.Query<UserEmailEntity>
(#"SELECT e.EmailId, e.ItemId, u.Username as FromUserName, e.EmailReceived
FROM User_Emails e
INNER JOIN User_Profile u on e.FromUserId = u.UserId
WHERE ToUserId = #userId and EmailStatus = #Status",
new { ToUserId = userId, Status = status })
.OrderBy(d => d.EmailReceived)
.Select(usrEmlEnt => usrEmlEnt.EmailId);
}
return new List<Int64>();
}
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
}
}
}