There are two tables: KindergartenIssues_Users and Users. Now I'm getting fileds of first table.However I could not get full name of user by UserId from 'Users' table.
I got data from 'Kindergartenissues_Users' table. How to correctly write incude to get full name by foreign key of UserId field?
public static async Task<List<KindergartenIssues_UsersView>> GetKinderGartenIssues()
{
List<KindergartenIssues_UsersView> users = new List<KindergartenIssues_UsersView>();
try
{
using (var entities = new WebPortalEntities())
{
users = await entities.KindergartenIssues_Users
.Where(k => k.DeletedDate == null)
.Select(k => new KindergartenIssues_UsersView()
{
ID = k.ID,
UserId = k.UserId,
RegDateWithFoundation = k.RegDateWithFoundation,
Year = k.Year,
AuthorId = k.AuthorId,
CreatedDate = k.CreatedDate,
ModifiedDate = k.ModifiedDate,
EditorId = k.EditorId,
DeletedDate = k.DeletedDate,
Description = k.Description,
ChildBirthYear = k.ChildBirthYear,
isHistory = k.isHistory
}).ToListAsync();
}
}
catch (Exception ex)
{
CommonHelper.WriteError($"GetKinderGartenIssues ERROR: {JsonConvert.SerializeObject(ex)}");
}
return users;
}
Try this
public static async Task<List<object>> GetKinderGartenIssues()
{
try
{
var users = new List<object>();
using (var entities = new WebPortalEntities())
{
users = await entities.KindergartenIssues_Users
.Where(k => k.DeletedDate == null)
.Join(entities.Users, o => o.UserId, i => i.UserId, (ki, u) => {
// You can obviously define your class somewhere instead of using anonymous object...
return new {
ID = ki.ID,
UserId = ki.UserId,
FullName = u.FullName
// etc...
};
}).ToListAsync();
}
}
catch (Exception ex)
{
CommonHelper.WriteError($"GetKinderGartenIssues ERROR: {JsonConvert.SerializeObject(ex)}");
}
return users;
}
Related
I'm new to C# and Linq.
Actually, I want to return anonymous types into list. anonymous types is contain of List, String, and DateTime. I tried with the code as below but its giving an error. please help and tell me what I am missing or suggest how can I achieve this.
//Error:
System.InvalidCastException: Specified cast is not valid..
//Edited C# Linq Code
public List<AuditInfo> GetScanAudit(object Id, DateTime? fromTime, DateTime? toTime, string type = null,
string user = null, Pager pager = null)
{
using (var ctx = new PlantDataContext())
{
var query = from audit in ctx.AuditLog
join ent in ctx.Scans on audit.RecordId equals ent.Id.ToString() into audits
from entaudits in audits.DefaultIfEmpty()
where audit.TypeFullName == "ABCD.DB.Model.Scan"
select new
{
audit,
entaudits
};
if (Id != null)
{
query = query.Where(x => x.audit.RecordId == Id.ToString());
}
if (fromTime.HasValue)
{
var tmp = new DateTimeOffset(fromTime.Value.ToUniversalTime());
query = query.Where(x => x.audit.EventDateUTC >= tmp);
}
if (toTime.HasValue)
{
var tmp = new DateTimeOffset(toTime.Value.ToUniversalTime());
query = query.Where(x => x.audit.EventDateUTC <= tmp);
}
if (!string.IsNullOrEmpty(type))
{
var parseEvent = (EventType)Enum.Parse(typeof(EventType), type);
query = query.Where(x => x.audit.EventType == parseEvent);
}
if (!string.IsNullOrEmpty(user))
{
query = query.Where(x => x.audit.UserName == user);
}
if (pager != null)
{
var totalRecords = query.Count();
pager.TotalRecords = totalRecords;
var data = query.Select(x =>
new AuditInfo
{
x.audit.TypeFullName, //Here Error Occurs
x.audit.UserName,//Here Error Occurs
x.audit.EventType,//Here Error Occurs
x.audit.EventDateUTC,//Here Error Occurs
#LogDetails = x.audit.LogDetails.ToList(), //Here Error Occurs
x.entaudits.Name,
#Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.Skip(pager.From)
.Take(pager.PageSize);
try
{
var list1 = data.ToList<AuditInfo>();
}
catch (Exception e)
{
}
var list = data.ToList<AuditInfo>();
pager.RecordCount = list.Count;
return list;
}
else
{
var list = query.Select(x =>
new AuditInfo
{
x.audit.TypeFullName,
x.audit.UserName,
x.audit.EventType,
x.audit.EventDateUTC,
#LogDetails = x.audit.LogDetails.ToList(),
x.entaudits.Name,
#Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.ToList<AuditInfo>();
return list;
}
}
}
When I debug the code totalRecords variable showing count 6, but is showing exception with message Specified cast is not valid at this line var list1 = data.ToList();
You have to cast the anonymous objects to dynamic.
To do this with linq you can use Cast<dynamic> linq method:
var list = query.Select(x =>
new
{
x.audit.TypeFullName,
x.audit.UserName,
x.audit.EventType,
x.audit.EventDateUTC,
#LogDetails = x.audit.LogDetails.ToList(),
x.entaudits.Name,
#Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.AsEnumerable()
.Cast<dynamic>()
.ToList<dynamic>(); \\ here exception occures
return list;
You can use strongly return type for your method like List<ClassName> instead of List<dynamic>
public List<ClassName> GetScanAudit(object Id, DateTime? fromTime, DateTime? toTime, string type = null, string user = null, Pager pager = null)
{
...
}
Then your query will be
var data = query.Select(x =>
new ClassName
{
TypeFullName = x.audit.TypeFullName,
UserName = x.audit.UserName,
EventType = x.audit.EventType,
EventDateUTC = x.audit.EventDateUTC,
LogDetails = x.audit.LogDetails.ToList(),
Name = x.entaudits.Name,
Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.Skip(pager.From)
.Take(pager.PageSize);
var list = data.ToList<ClassName>();
And your strongly type class look like
public class ClassName
{
public string TypeFullName { get; set; }
public string UserName { get; set; }
public string EventType { get; set; }
public DateTime EventDateUTC { get; set; }
public List<LogDetail> LogDetails { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Make sure the datatype of each property should match in your .Select clause in query
Edit:
if (pager != null)
{
var totalRecords = query.Count();
pager.TotalRecords = totalRecords;
var data = query.Select(x =>
new AuditInfo
{
TypeFullName = x.audit.TypeFullName,
UserName = x.audit.UserName,
EventType = x.audit.EventType,
EventDateUTC = x.audit.EventDateUTC,
LogDetails = x.audit.LogDetails.ToList(),
Name = x.entaudits.Name,
Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.Skip(pager.From)
.Take(pager.PageSize);
try
{
var list1 = data.ToList<AuditInfo>();
}
catch (Exception e)
{
}
var list = data.ToList<AuditInfo>();
pager.RecordCount = list.Count;
return list;
}
else
{
var list = query.Select(x =>
new AuditInfo
{
TypeFullName = x.audit.TypeFullName,
UserName = x.audit.UserName,
EventType = x.audit.EventType,
EventDateUTC = x.audit.EventDateUTC,
LogDetails = x.audit.LogDetails.ToList(),
Name = x.entaudits.Name,
Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.ToList<AuditInfo>();
return list;
}
I am new to LINQ, and i am getting this error message :
{"error":"Explicit construction of entity type 'Proj.Models.Ad' in
query is not allowed."}
I am using this code to retrieve the data
public ActionResult favads()
{
bool isValid = false;
string authToken = "";
if (Request["dt"] != null)
authToken = Request["dt"].ToString().Trim();
else
return Content("{\"error\":\"Please send device token parameter 'dt'.\"}", "application/json");
string message = (new CommonFunction()).ValidateToken(authToken, out isValid);
if (isValid)
{
long userID = 0;
if (Request["userID"] != null)
long.TryParse(Request["userID"].ToString().Trim(), out userID);
else
return Content("{\"error\":\"Please send user id parameter 'userID'.\"}", "application/json");
if (userID < 1)
return Content("{\"error\":\"Please select appropriate user to view details.\"}", "application/json");
try
{
var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) && Favtb.StatusID.Equals(1)).Select(p => new Ad() { ID = p.AdID.Value, CategoryID = int.Parse(p.CategoryID.ToString()) })
from c in db.Ads.Where(Adstb => Adstb.ID == d.ID).DefaultIfEmpty()
select new
{
FavId = d.ID,
c.ID,
c.Category.ParentCategoryID,
c.Category.CategoryID,
c.Category.LogoFile,
c.Category.CatName,
c.AdTitle,
AdDescription = (c.AdDescription.Length > 50 ? c.AdDescription.Substring(0, 50) : c.AdDescription),
c.CityID,
c.Price,
c.CreationDate,
c.Photos,
c.VideoUrl,
c.IsMobileVisibile
};
int pg = 0;
if (Request["p"] != null)
int.TryParse(Request["p"], out pg);
string _sortby = "MRF";
if (Request["sortby"] != null)
_sortby = Request["sortby"];
if (_sortby.Equals("OF"))
q = q.OrderBy(ad => ad.CreationDate.Value);
else if (_sortby.Equals("PD"))
q = q.OrderByDescending(ad => ad.Price.Value);
else if (_sortby.Equals("PA"))
q = q.OrderBy(ad => ad.Price.Value);
else
q = q.OrderByDescending(ad => ad.CreationDate.Value);
return Json(q.ToList().Skip(pg * recordsPerPage).Take(recordsPerPage), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Content("{\"error\":\"" + ex.Message + "\"}", "application/json");
}
}
else
{
return Content("{\"error\":\"" + message + "\"}", "application/json");
}
}
Ads class
public class Ads : Ad
{
public long ID { get; set; }
public string FashionType { get; set; }
public string ForRentSale { get; set; }
public string ForJobHire { get; set; }
public string JobTypeID { get; set; }
}
Ad is also mapped and you cannot project a new instance of it like this in a query. See this question.
What you can do is just create an anonymous type or even better in this case, since in your query you only use the ID of the Ad object retrieve just that:
var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) &&
Favtb.StatusID.Equals(1))
.Select(p => p.AdID.Value)
from c in db.Ads.Where(Adstb => Adstb.ID == d).DefaultIfEmpty()
select new
{
FavId = d,
c.ID,
c.Category.ParentCategoryID,
/* ... */
};
I recommend you look into Navigation Properties. I think it will make this query look neater
Also maybe look at this option instead of using the Method Syntax for the first table, might be more readable:
var q = from d in db.AdsFavourites
//In this case also no need for `Equals` - you are comparing value types
where d.CreateBy == userID && d.StatusID == 1
from c in db.Ads.Where(Adstb => Adstb.ID == d.AdID.Value).DefaultIfEmpty()
select new
{
FavId = d.AdID.Value,
c.ID,
/* ... */
};
I want to get two table combine data using linq c# lambda expression and get fix number of column get in the list.
I have try this code but I don't know how to write query in linq lambda expression.
this is my method:
public ActionResult GetUserList(string searchRequest)
{
List<User> userList = new List<User>();
if (searchRequest != null)
{
if (searchRequest == "All")
{
// here i want to write select query but how i don't know
userList = db.user.ToList();
}
else if (searchRequest == "Flight")
{
userList = db.user
.Where(t => t.type_id == (int)ServiceTypeEnum.Flight)
.ToList();
}
}
return Json(new { data = userList });
}
any one have the idea about this query then please let me know how can do.
The issue that you will experience with lambdas where you select specific fields is that the result is normally an anonymous type. Anonymous types from two different queries cannot easily be joined together in a list because the compiler cannot verify the structure or equality of the types.
There are other ways around this...
The best practice approach is to create a formal type definition and use that so that you can manipulate your objects outside of your lambda expressions. Note here that I have assumed a simple example structure that is a sub-set of user:
public ActionResult GetUserList(string searchRequest)
{
try
{
List<UserSearchResult> UserList = new List<UserSearchResult>();
if (searchRequest != null)
{
if (searchRequest == "All")
{
UserList.AddRange(db.user.Select(u => new UserSearchResult { Title = u.Title, FirstName = u.Firstname, LastName = u.Lastname })); // here i want to write select query but how i don't know
}
else if (searchRequest == "Flight")
{
UserList.AddRange(db.user.Where(t => t.type_id == (int)ServiceTypeEnum.Flight)
.Select(u => new UserSearchResult { Title = u.Title, FirstName = u.Firstname, LastName = u.Lastname }));
}
}
return Json(new { data = UserList });
}
catch (Exception ex)
{
throw;
}
return Json(null);
}
public class UserSearchResult
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Because we have explicitly cast the result of our selection of specific fields to a formal type, we can now use that type in operations outside of your queries and can even manipulate the values.
Define UserDto class for columns that you want select
public class UserDto
{
public int Id{get;set;}
public int Name{get;set;}
//Other Properties
}
Then change your code to following
public ActionResult GetUserList(string searchRequest)
{
try
{
if (searchRequest != null)
{
IQueryable<User> query;
if (searchRequest == "All")
{
query = db.user.AsQueryable(); // here i want to write select query but how i don't know
}
else if (searchRequest == "Flight")
{
UserList = db.user.Where(t => t.type_id == (int)ServiceTypeEnum.Flight);
}
if(query != null)
{
var list = query.Select(e=> new UserDto
{
Id = e.Id,
Name = e.Name
//Other properties
}).ToList();
return Json(new { data = list });
}
}
}
catch (Exception ex)
{
throw;
}
return Json(null);
}
I think the local variable is holding you back. Just return the result you want.
public ActionResult GetUserList(string searchRequest)
{
if (searchRequest == "All")
{
var users = db.user
.Select(user => new {user.Name, user.Address.ZipCode})
.ToList();
return ToJson(users);
}
else if (searchRequest == "Flight")
{
List<User> users = db.user
.Where(t => t.type_id == (int)ServiceTypeEnum.Flight)
.ToList();
return ToJson(users);
}
return ToJson(new List<User>());
}
private ActionResult ToJson<T>(T list)
{
return Json(new { data = list });
}
Several time, i need to get the name of user in AplicationUsers (aspnetusers). Like in Chamado model (table) i have a column Id_Agente (user). With a simple List, i will get something like:
"3q0aju9-9ijuso-9sodkci..."
public class Chamado
{
public int Id { get; set; }
public DateTime Abertura { get; set; }
public string Titulo { get; set; }
public string Descricao { get; set; }
public string Id_Agente { get; set; }
[NotMapped]
public String NomeAgente { get; set; }
}
To work around, I created a NotMapped field and filled it with a foreach:
using (IdentityContext id2 = new IdentityContext())
{
foreach (var item in historicos)
{
item.NomeAgente = id2.Users
.Where(u => u.Id == item.Id_Agente)
.Select(u => u.Nome).FirstOrDefault();
}
}
But now I need to group Chamados by Agente, and it's becoming more and more harder, to work around. I tried to make another notMapped on chamados model named Qtde, make a list and extract from that list but returned a error:
public List<PainelChamados> ListarOrdem()
{
using (SistemaContext db = new SistemaContext())
{
var chamados = db.Chamado
.Where(c => c.Situacao != Chamado.Esituacao.Concluido)
.GroupBy(c => c.Id_Agente)
.Select(c => new Chamado { Id_Agente = c.Key, Qtde = c.Count() });
using (IdentityContext id2 = new IdentityContext())
{
foreach (var item in chamados)
{
item.NomeAgente = id2.Users
.Where(u => u.Id == item.Id_Agente)
.Select(u => u.Nome).FirstOrDefault();
}
}
var query = chamados
.Select(c => new PainelChamados
{
Agente = c.NomeAgente,
Qtde = c.Qtde
});
return query.ToList();
}
}
Last, but not least, how could I just Include aspnetusers table like another regular table:
var query = db.Suporte_Projeto
.Include(l => l.Licenciado)
.Include(c => c.Condominio)
.Include(pr => pr.ProjetoProduto)
.Include(p => p.ProjetoAcesso);
Chart Data
Error
I did another work around! It's seems to be a good option while i cant join aspnetusers to my models table:
public List<PainelChamados> ListarOrdem()
{
using (SistemaContext db = new SistemaContext())
{
var query = db.Chamado
.Where(c => (c.Situacao != Chamado.Esituacao.Concluido && c.Id_Agente != null))
.GroupBy(e => new { e.Id_Agente})
.Select(lg => new PainelChamados
{
CodAgente = lg.Key.Id_Agente,
Qtde = lg.Count()
});
UsuarioData ud = new UsuarioData();
List<PainelChamados> Lista = new List<PainelChamados>();
foreach (var item in query)
{
Lista.Add(new PainelChamados
{
CodAgente = item.CodAgente,
Agente = item.CodAgente == null ? string.Empty : ud.GetAgenteId(item.CodAgente),
Qtde = item.Qtde
});
}
return Lista;
}
}
What do you think, is it the best way to work around? I could return the list i desired.
Chart With Agente Names
I'm new to the RavenDB and I am struck with a condition here.Basically this is what I want to achive I have a list of the employees in the RavenDB and I need to fetch employees who are not of the type "Contract".I tried to use basic linq query but I am unable to resolve the issue as I am geting exceptions like "Method Not Supported" and "Cannot understand how to translate ... etc".
This is what I have tried untill now.
class Program
{
static void Main(string[] args)
{
using (var documentStore = new DocumentStore() { ConnectionStringName = "RavenDBConnectionString" })
{
documentStore.Initialize();
/* using (var session = documentStore.OpenSession())
{
session.Store(new User { Id = 1, Roles = new List<Role> { new Role { Type = UserType.Contract }, new Role { Type = UserType.Developer } } });
session.Store(new User { Id = 2, Roles = new List<Role> { new Role { Type = UserType.Permanent }, new Role { Type = UserType.Developer } } });
session.Store(new User { Id = 3, Roles = new List<Role> { new Role { Type = UserType.SeniorDeveloper }, new Role { Type = UserType.Manager } } });
session.Store(new User { Id = 4, Roles = new List<Role> { new Role { Type = UserType.Contract }, new Role { Type = UserType.SeniorDeveloper } } });
session.Store(new User { Id = 5, Roles = new List<Role> { new Role { Type = UserType.Permanent }, new Role { Type = UserType.Manager } } });
session.Store(new User { Id = 6, Roles = new List<Role> { new Role { Type = UserType.Contract }, new Role { Type = UserType.Developer } } });
session.SaveChanges();
}*/
using (var session = documentStore.OpenSession())
{
//var nonContractEmployees = session.Query<User>().Where(x => !x.Roles.Exists(y => y.Type == UserType.Contract)).ToList();
var nonContractEmployees = session.Query<User>().Where(x => x.Roles.Count(y => y.Type == UserType.Contract) == 0).ToList();
// var nonContractEmployees = session.Query<User>().Where(x => !x.Roles.Contains(x.Roles.FirstOrDefault(y => y.Type == UserType.Contract))).ToList();
//var nonContractEmployees = session.Query<User>().Where(x => x.Roles.FirstOrDefault(y => y.Type == UserType.Contract) == null).ToList();
}
}
}
}
public class User
{
public int Id { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public UserType Type { get; set; }
}
public enum UserType
{
Manager,
Permanent,
Contract,
Developer,
SeniorDeveloper
}
I would really appretiate it if someone can help me in resolving this issue.
Thanks,
Kapil
Edit 1
var nonContractEmployees = session.Query<User>()
.Where(x => !x.Roles.In(new [] {new Role { Type = UserType.Contract}))
.ToList();
Edit 2
This works but isn't efficient.
using (var session = documentStore.OpenSession())
{
var nonContractEmployees = session.Query<User>()
.ToList()
.Where(x => x.Roles.Contains(
new Role {Type = UserType.Contract},
new RoleComparer()));
}
public class RoleComparer : IEqualityComparer<Role>
{
public bool Equals(Role x, Role y)
{
return
x == null && y == null ||
x != null &&
y != null &&
x.Type == y.Type;
}
public int GetHashCode(Role obj)
{
return
obj == null
? 0
: obj.Type.GetHashCode();
}
}
Try:
var nonContractEmployees = session.Query<User>()
.Where(x => !x.Roles.Any(y => y.Type == UserType.Contract))
.ToList();
I've updated my Query with what it should be. (currently failing)
And I've submitted a failing test to Ayende to your query on the Google Group.
https://groups.google.com/forum/?fromgroups#!topic/ravendb/LpSo3VdkavI