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>();
}
Related
Im trying to map the list of Products and CategoryPictures properties inside the Category entity.
Then im mapping the Picture object inside the CategoryPictures.
Im not sure if this an effiecient way of using dapper as its my first time working with dapper. I used to work with entityframework.
Im using Dapper instead of EF as i want to improve my sql skills.
Should i use multiple results instead?
public async Task<IEnumerable<Category>> GetCategoriesListAsync()
{
using (var conn = SqlConnection())
{
string sql = #"select c.*, cp.*, pd.*, p.*
from Categories c
inner join CategoryPictures cp on cp.CategoryId = c.Id
inner join Products pd on pd.CategoryId = c.Id
inner join Pictures p on p.Id = cp.PictureId";
//string sqlmulti = $#"select * from {tableName};
// select * from Products";
//List<Category> cat = null;
//List<Product> prod = null;
//using (var lists = conn.QueryMultiple(sqlmulti))
//{
// cat = lists.Read<Category>().ToList();
// prod = lists.Read<Product>().ToList();
//}
var lookup = new List<Category>();
await conn.QueryAsync<Category, CategoryPicture, Product, Picture, Category>(sql,
(c, cp, pd, p) =>
{
if (lookup.FirstOrDefault(x => x.Id == c.Id) == null)
{
lookup.Add(c);
}
c.CategoryPictures.AsList().Add(cp);
c.Products.AsList().Add(pd);
foreach (var item in c.CategoryPictures)
{
item.Picture = p;
}
return null;
});
return lookup;
}
}
I've removed the link between Category and Product where the Product was child of Category.
The problem i was having with the previous code was that the Picture child of CategoryPictures was not populating properly. So i set the Picture object of CategoryPicture before populating CategoryPicture.
public async Task<IEnumerable<Category>> GetAllCategories()
{
using (var conn = SqlConnection())
{
string sql = #"select c.Id, c.Name, c.Description, c.Created, c.LastModified,
cp.Id, cp.CategoryId, cp.PictureId,
p.Id, p.Url
from Categories c
inner join CategoryPictures cp on cp.CategoryId = c.Id
inner join Pictures p on p.Id = cp.PictureId";
var lookup = new Dictionary<int, Category>();
await conn.QueryAsync<Category, CategoryPicture, Picture, Category>(sql,
(c, cp, p) =>
{
if (!lookup.TryGetValue(c.Id, out Category found))
{
lookup.Add(c.Id, found = c);
}
cp.Picture = p;
found.CategoryPictures.AsList().Add(cp);
return null;
});
return lookup.Values.ToList();
}
}
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).
I am still getting familiar with SQL and LINQ and I am trying to get every objects and its objects which is under one ID.
The below is the EDMX Diagram.
I am passing ClientID and I want to list everything that is under that ClientID and the below is my query to do so but as you can see query is only returning the first element but how to change it to return the list of every elements as below:
Passed ClientID
THeaderTitle 1
TReportName 1
TReportName 2
MY query is below which is returning the first element:
public TReportHeaderModel GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
}).First();
return query;
}
}
I've got it working!
I had to change it in my interface as
IList GetHeadersByClient (int ClientID);
So that I can return List of elements in my controller to pass to view.
public IList<TReportHeaderModel> GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
});
return query.ToList();
}
}
I have two tables containing following columns:
SELECT TOP 1000 [Id]
,[UserId]
,[MenuId]
,[parentid]
FROM [TravelEnterDB].[dbo].[UserAccess]
SELECT TOP 1000 [Id]
,[Title]
,[parentId]
,[IsActive]
,[Url]
,[OrderMenu]
,[IconName]
FROM [TravelEnterDB].[dbo].[AdminMenu]
so here is the deal,i want to show all of the 'AdminMenu' records with 'parenId=0' in a table in MVC and i want to tick the items which have been given to a specific user by 'UserId'.I have some codes but they are not working correctly.
Here is the code:
public ActionResult ADDAccess(int? id, string UserId)
{
List<MenuClass> model = new List<MenuClass>();
var result =(from adminMenu in db.AdminMenus
where adminMenu.parentId == 0
select new
{
adminMenu.Id,
adminMenu.IsActive,
adminMenu.OrderMenu,
adminMenu.Title,
adminMenu.Url,
adminMenu.parentId,
adminMenu.IconName,
});
var users = db.UserAccesses.Where(p => p.UserId == UserId).ToList();
var t = (from m in users
join r in result on m.MenuId equals r.Id
select new
{
r.Id,
r.IsActive,
r.OrderMenu,
r.Title,
r.Url,
r.parentId,
r.IconName,
m.UserId,
m.MenuId
}).ToList();
foreach (var item in t)
{
MenuClass menu = new MenuClass();
menu.IconName = item.IconName;
menu.IsActive = item.IsActive;
menu.Title = item.Title;
menu.Url = item.Url;
menu.Id = item.Id;
if (item.Id == item.MenuId && item.UserId == UserId)
{
menu.IsChecked = true;
}
menu.parentId = (int)item.parentId;
model.Add(menu);
}
return View(model);
}
Sort in LINQ
I have 2 database CustomerEntities and BillEntities
I want to get CustomerName from CustomerEntities and sort it but it have no data and I want .ToList() just once time because it slow if used many .ToList()
using (var db1 = new CustomerEntities())
{ using (var db2 = new BillEntities())
{
var CustomerData = db1.Customer.Select(s=> new{s.CustomerCode,s.CustomerName}).ToList();
var BillData = (from t1 in db2.Bill
select new {
BillCode = t1.Billcode,
CustomerCode = t1.Customer,
CustomerName = ""; //have no data
});
}
if(sorting.status==true)
{
BillData= BillData.OrderBy(o=>o.CustomerName); //can't sort because CustomerName have no data
}
var data = BillData .Skip(sorting.start).Take(sorting.length).ToList(); // I want .ToList() just once time because it slow if used many .ToList()
foreach (var b in data)
{
var Customer = CustomerData.FirstOrDefault(f => f.CustomerCode==b.CustomerCode );
if(CustomerName>!=null)
{
r.CustomerName = Customer.CustomerName; //loop add data CustomerName
}
}
}
I have no idea to do it. Help me please
I'm not sure if I understand your code but what about this:
var BillData = (from t1 in db2.Bill
select new {
BillCode = t1.Billcode,
CustomerCode = t1.Customer,
CustomerName = db1.Customer.FirstOrDefault(c => c.CustormerCode == t1.Customer)?.CustomerName
});
Then you have objects in BillData that holds the CustomerName and you can order by that:
BillData.OrderBy(bd => bd.CustomerName);
If you just want to get CustomerName from your customer Db and sort it, this is what i would have used. I used orderByDescending but you can use OrderBy aswell.
public List<Customer> getLogsByCustomerName(string customername)
{
using (var dbentites = new CustomerEntities())
{
var result = (from res in dbentites.Customer.OrderByDescending(_ => _.CustomerName)
where res.CustomerName == customername
select res).ToList();
return result.ToList();
}
}