How to use SingleOrDefault/where in IEnumerable Session property - c#

I'm using VS2010 Entity Framework to store a value in a session. I the use syntax below:
private IEnumerable _TransactionItem2
{
get
{
var msg = HttpContext.Current.Session["SESSION_MESSAGES_NAME"] as IEnumerable;
if (msg == null)
{
msg = new BOMDetailController().GetSearchData(0, 0);
HttpContext.Current.Session["SESSION_MESSAGES_NAME"] = msg;
}
return msg;
}
set
{
Session[_MenuName + "TransactionItem"] = value;
}
}
Session initialization method below:
public IEnumerable GetSearchData(int companyID = 0, long bOMID = 0)
{
var itemBrand = (from p in this.controllerCMN.Context.CmnItemBrands where p.IsDeleted == false select p).AsEnumerable();
var itemColor = (from p in this.controllerCMN.Context.CmnItemColors where p.IsDeleted == false select p).AsEnumerable();
var itemMaster = (from p in this.controllerCMN.Context.CmnItemMasters where p.IsDeleted == false select p).AsEnumerable();
var itemSpecificationMaster = (from p in this.controllerCMN.Context.CmnItemSpecificationMasters where p.IsDeleted == false select p).AsEnumerable();
var itemStyleMaster = (from p in this.controllerCMN.Context.CmnItemStyleMasters where p.IsDeleted == false select p).AsEnumerable();
var uOM = (from p in this.controllerCMN.Context.CmnUOMs where p.IsDeleted == false select p).AsEnumerable();
var bnOMMaster = (from p in this.Context.PlnBOMMasters where p.IsDeleted == false && p.CompanyID == companyID select p).AsEnumerable();
var prdPhase = (from p in this.Context.PlnPrdPhases where p.IsDeleted == false && p.ComapnyID == companyID select p).AsEnumerable();
var prdTask = (from p in this.Context.PlnPrdTasks where p.IsDeleted == false && p.ComapnyID == companyID select p).AsEnumerable();
var bOMDetail = (from p in this.Context.PlnBOMDetails where p.IsDeleted == false && p.CompanyID == companyID select p).AsEnumerable();
var query = from p in bOMDetail
select new
{
BOMDetailRecordID = p.BOMDetailRecordID,
CustomCode = p.CustomCode,
BOMID = p.BOMID,
BOMName = (from q in bnOMMaster where q.BOMID == p.BOMID select q.Description).FirstOrDefault(),
PhaseID = p.PhaseID,
PhaseName = (from q in prdPhase where q.PhaseID == p.PhaseID select q.PhaseName).FirstOrDefault(),
ItemID = p.ItemID,
ItemName = (from q in itemMaster where q.ItemID == p.ItemID select q.ItemName).FirstOrDefault(),
ColorID = p.ColorID,
ColorName = (from q in itemColor where q.ColorID == p.ColorID select q.ColorName).FirstOrDefault(),
StyleID = p.StyleID,
StyleName = (from q in itemStyleMaster where q.StyleID == p.StyleID select q.StyleName).FirstOrDefault(),
ItemSpecificationID = p.ItemSpecificationID,
ItemSpecificationName = (from q in itemSpecificationMaster where q.ItemSpecificationID == p.ItemSpecificationID select q.Description).FirstOrDefault(),
ItemBrandID = p.ItemBrandID,
BrandName = (from q in itemBrand where q.ItemBrandID == p.ItemBrandID select q.ItemBrandName).FirstOrDefault(),
UOMID = p.UOMID,
UOMName = (from q in uOM where q.UOMID == p.UOMID select q.UOMName).FirstOrDefault(),
ItemQty = p.ItemQty,
UnitPrice = p.UnitPrice,
StatusID = p.StatusID,
};
return query.WhereIf(bOMID != 0, p => p.BOMID == bOMID).OrderByDescending(w => w.BOMDetailRecordID);
}
I want to query on the above property TransactionItem2.
1) I want to count how many items on the property TransactionItem2
`TransactionItem2.AsQueryable().Count()`
2) I want to query on this like:
var entity = _ TransactionItem2.SingleOrDefault(item => item.BOMDetailRecordID == childRecordID);
3) I want to use a query
var entity = _ TransactionItem2.Where(item => item.BOMDetailRecordID == childRecordID);
My Extension method is
public static TSource Single<TSource>(this IEnumerable source)
{
return source.Cast<TSource>().Single();
}
public static TSource Single<TSource>(this IEnumerable source, Func<TSource, bool> predicate)
{
return source.Cast<TSource>().Single(predicate);
}
public static TSource SingleOrDefault<TSource>(this IEnumerable source)
{
return source.Cast<TSource>().SingleOrDefault();
}
public static TSource SingleOrDefault<TSource>(this IEnumerable source, Func<TSource, bool> predicate)
{
return source.Cast<TSource>().SingleOrDefault(predicate);
}
Working syntax:
var entity = _TransactionItem2.SingleOrDefault(item => item.BOMDetailRecordID == childRecordID);
The above syntax shows an error message:
“cannot be inferred from the usage. Try specifying the type arguments
explicitly”
The above syntax is not working for the property TransactionItem2. Why is 1,2,3 not working?

You have to specify TSource explicitly when calling your methods:
var entity = _TransactionItem2.SingleOrDefault<EntityClass>(item => item.BOMDetailRecordID == childRecordID);

Related

LinqToSQL returning IQueryable

My interface is returning a IQueryable. The model TemplatesAgent with a template and IEnumerable<Agent> object. In my DataService I am collecting all of the agents in the ListOfAgent. I am then selecting the agent that are within the templates using the AgentVersionKey. This is the error I am getting is it related to the IQueryable type?
ExceptionMessage": "Explicit construction of entity type 'OrderTemplateTool.Data.Agent' in query is not allowed.",
Interface
IQueryable<TemplatesAgent> GetTemplateAgentNameDiseaseName(string agent, string disease);
DataService
public IQueryable<TemplatesAgent> GetTemplateAgentNameDiseaseName(string agent, string disease)
{
//Common
var ListOfAgent = (from a in UnitOfWork.GetRepository<Agent>().Get(a => !a.IsDeleted && a.IsCurrentVersion)
select new Agent
{
VersionKey = a.VersionKey,
Name = a.Name,
RxNormId = a.RxNormId,
BrandNames = a.BrandNames
});
var TemplatesAgent = (from t in UnitOfWork.GetRepository<Template>().Get()
join r in UnitOfWork.GetRepository<Regimen>().Get() on t.Id equals r.TemplateId
join rp in UnitOfWork.GetRepository<RegimenPart>().Get() on r.Id equals rp.RegimenId
join re in UnitOfWork.GetRepository<RegimenEntry>().Get() on rp.Id equals re.RegimenPartId
where t.IsCurrentVersion
&& t.Status == 7
select new TemplatesAgent
{
Template = t,
Agent = ListOfAgent.Where(x => x.VersionKey == re.AgentVersionKey).ToList()
});
Model
public class TemplatesAgent
{
public Template Template { get; set; }
public IEnumerable<Agent> Agent { get; set; }
}
Controller
[HttpGet]
public IHttpActionResult TemplatesList(string key, string disease = null, string agent = null)
{
var result = TemplatesDataService.GetTemplateAgentNameDiseaseName(agent, disease)
.Where(
t =>
t.Template.IsCurrentVersion && t.Template.Status == (short)TemplateMode.Published)
.OrderBy(t => t.Template.TemplateIdMain)
.ThenBy(t => t.Template.TemplateIdNumeric)
.ThenBy(t => t.Template.TemplateIdAlt)
.ToList()
.Select(t => new
{
TemplateId = t.Template.TemplateId,
RegimenTitle = t.Template.Title,
CourseTitle = t.Template.GroupTitle,
GuidelineTitle = t.Template.GuideLineTitle,
DiseaseId = t.Template.ExternalDiseaseId,
DiseaseName = t.Template.DiseaseName
Agent = t.Agent(a => new
{
VersionKey = a.VersionKey,
Name = a.Name,
BrandNames = a.BrandNames,
RxNormId = a.RxNormId
}).ToList(),
})
.Distinct().ToList();
return Json(result);
}
It is telling you that you can't make a new Agent inside the query. Try this.
var agentRepo = UnitOfWork.GetRepository<Agent>().Get();
var ListOfAgent = (from a in agentRepo
where !a.IsDeleted && a.IsCurrentVersion
select a);
var TemplatesAgent = (from t in UnitOfWork.GetRepository<Template>().Get()
join r in UnitOfWork.GetRepository<Regimen>().Get() on t.Id equals r.TemplateId
join rp in UnitOfWork.GetRepository<RegimenPart>().Get() on r.Id equals rp.RegimenId
join re in UnitOfWork.GetRepository<RegimenEntry>().Get() on rp.Id equals re.RegimenPartId
where t.IsCurrentVersion
&& t.Status == 7
select new TemplatesAgent
{
Template = t,
Agent = ListOfAgent.Where(x => x.VersionKey == re.AgentVersionKey).ToList()
});
Controller
[HttpGet]
public IHttpActionResult TemplatesList(string key, string disease = null, string agent = null)
{
var result = TemplatesDataService.GetTemplateAgentNameDiseaseName(agent, disease)
.Where(
t =>
t.Template.IsCurrentVersion && t.Template.Status == (short)TemplateMode.Published)
.OrderBy(t => t.Template.TemplateIdMain)
.ThenBy(t => t.Template.TemplateIdNumeric)
.ThenBy(t => t.Template.TemplateIdAlt)
.Distinct().ToList();
return Json(result);
}

Apply multiple order by in linq

I am trying to sort my list by applying two order by. I just want to sort my list by the following orders:
Order 1: DateTime Descending Order
Order 2: Level Ascending Order
Following is my code:
First Method:
var FinalQuery = (from s in data
join p in context.A on s.Id equals p.PId
join PR in context.P on s.RP equals PR.PId
where PR.PId == s.PId
&& PR.IsActive == true
select new List
{
//columns
});
Model.TotalRecord = FinalQuery.Count();
if (Model.IsExportData == false)
{
Model.ListItems = FinalQuery
.Skip(Filter.PageNumber == 0 ? 0 : Model.RecordPerPage * (Filter.PageNumber - 1))
.Take(Model.RecordPerPage).ToList();
Model.ListItems.OrderByDescending(x => x.LoggedDateTime.Value.Date).ThenBy(x => x.Level);
}
else
{
Model.ListItems = FinalQuery.ToList();
}
Second Method:
var FinalQuery = (from s in data
join p in context.A on s.Id equals p.PId
join PR in context.P on s.RP equals PR.PId
where PR.PId == s.PId
&& PR.IsActive == true
select new List
{
//columns
});
Model.TotalRecord = FinalQuery.Count();
if (Model.IsExportData == false)
{
Model.ListItems = FinalQuery
.OrderByDescending(x => x.LoggedDateTime.Value.Date)
.ThenBy(x => x.Level)
.Skip(Filter.PageNumber == 0 ? 0 : Model.RecordPerPage * (Filter.PageNumber - 1))
.Take(Model.RecordPerPage).ToList();
}
else
{
Model.ListItems = FinalQuery.ToList();
}
I am not getting the actual result.
You don't assign the result of your OrderBy Linq-Chain in your first method.
Instead of
Model.ListItems.OrderByDescending(x => x.LoggedDateTime.Value.Date)
.ThenBy(x => x.Level);
you have to assign it to something like
var result = Model.ListItems.OrderByDescending(x => x.LoggedDateTime.Value.Date)
.ThenBy(x => x.Level);
As you can see from the sources:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
return new OrderedEnumerable<TSource, TKey>(source, keySelector, null, false);
}
The OrderBy returns a new OrderedEnumerable, where the Sort()-Method of a list works on the list itself.
System.Collections.Generic.List.Sort
public void Sort()
{
Sort(0, Count, null);
}

cannot implicitly convert type 'syste.collections.generics.list' to 'system.collections.generics.list'

I'm getting error:
Cannot implicitly convert type System.Collections.Generics.List<MeritMaste_QuestionPeparsettings> to System.Collections.Generics.List<MeritMaste.data.MeritMAster_QuestionPeparSettng>
is it a database connection problem ?
is it a database connection error?
public class DataManager
{
public static void OnlineExamLists(
out List<MeritMaste_QuestionPaperSettings> examQuestionSettings,
out List<MeritMaster_QuestionBank> questionBanks, string examCode)
{
using (var dbcontext = new meritmasterEntities())
{
// var exam_code = dbcontext.MeritMaste_QuestionPaperSettings.Where(m => m.ID == examCode).FirstOrDefault().ex_code;
//(from k in dbcontext.MeritMaste_QuestionPaperSettings where k.Status == true && k.ID == examCode select k.ex_code).ToList();
examQuestionSettings = (from k in dbcontext.MeritMaste_QuestionPaperSettings
where k.Status == true && k.ex_code == examCode
select k).ToList();
var examsettingslocal = examQuestionSettings.FirstOrDefault();
var kabqu = new List<MeritMaster_QuestionBank>();
var queBank = examsettingslocal == null
? kabqu
: (from k in dbcontext.MeritMaster_QuestionBank
where k.Status == true && k.Course_ID == examsettingslocal.CourseId
select k).ToList();
// questionBanks = queBank.ToList();
var questionbanklocal = dbcontext.MeritMaste_QuestionPaperSettings.ToList();
questionBanks = (from es in examQuestionSettings.ToList()
join qb in queBank.ToList() on new {p1 = (int) es.CourseId, p2 = (int) es.QuestionIds} equals
new {p1 = (int) qb.Course_ID, p2 = (int) qb.ID}
where es.ex_code == examCode && es.Status == true && qb.Status == true
select qb).ToList();
//join a in questionpaperlocal.ToList() on k.QuestionIds equals a.ID
//where k.Status == true && a.Status == true
////orderby a.Id ascending
//select k
}
}
}
MeritMaste_QuestionPeparsettings and MeritMaste.data.MeritMAster_QuestionPeparSettng are two different types to the compiler, and there doesn't exist a convertion between these two types.
You need to either define a conversion (implicit or explicit), or manually convert them. You can do so using various techniques, such as using IQueryable.ForAll, or IEnumerable.Select extension methods.

Method'' has no supported translation to SQL

I want to, in the midst of a linq to sql query where clause, check against a public int. I am getting this error: Method 'Int32 isInDept(System.String)' has no supported translation to SQL.
Vaguely related classes (from a public static class called ad):
//get AD property
public static string GetProperty(this Principal principal, String property) {
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
if (directoryEntry.Properties.Contains(property))
return directoryEntry.Properties[property].Value.ToString();
else
return String.Empty;
}
public static string GetDepartment(this Principal principal) {
return principal.GetProperty("department");
}
The Classes in question (from a different class):
public int isInDept(string department) {
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(domain, GetUserId());
if (department == userPrincipal.GetDepartment()) {
return 3;
}
else { return 2; }
}
public intranetGS.viewArticle viewArticle(int id) {
string user = GetUserId();
var result = ( from a in n.articles
join s in n.sections on a.section equals s.section_id
join p in n.privacies on a.privacy equals p.privacy_id
let iid = isInDept(s.name)
where (a.active == true && a.article_id == id && a.privacy < iid) ||
(a.active == true && a.article_id == id && a.privacy == 3 && a.author == user)
select new intranetGS.viewArticle {
articleId = a.article_id,
title = a.title,
author = a.author,
html = a.html,
section = s.name,
privacy = p.name,
dateCreated = a.date_created,
dateModified = a.date_modified,
userCreated = a.user_created,
userModified = a.user_modified
}).First();
var nv = (from v in n.navs
join s in n.sections on v.section equals s.section_id
let iid = isInDept(s.name)
where (v.active == true && s.name == result.section && v.privacy < 3) ||
(v.active == true && s.name == result.section && v.privacy == iid && v.user_created == user)
select v.html);
StringBuilder sb = new StringBuilder();
foreach (var r in nv) {
sb.Append(nv);
}
result.articleNav = sb.ToString();
return result;
}
What am I doing wrong? If I can't do it this way, how is it suggested that it be done?
It is not possible to translate that function to SQL, one workaround for this is to make most of your query with linq to sql, and use Linq to Objects for the rest. It should be something like this:
var query = ( from a in n.articles
join s in n.sections on a.section equals s.section_id
join p in n.privacies on a.privacy equals p.privacy_id
where (a.active == true && a.article_id == id)
select new intranetGS.viewArticle {
articleId = a.article_id,
title = a.title,
author = a.author,
html = a.html,
section = s.name,
privacy = p.name,
privacyId = a.privacy,
dateCreated = a.date_created,
dateModified = a.date_modified,
userCreated = a.user_created,
userModified = a.user_modified
}).ToList();
And then filter the list:
var result = query.Where(a => (a.privacyId < isInDept(a.section)) ||
(a.privacyId == 3 && a.author == user)).First();
Then you can do the same for the second query.

Join LINQ with a List<> in select new

hi first time im asking here so il try to do it correctly
i have a problem im making a shopping basket and im nearly there but always a but
what i want to have is something like this
List<HKurv> KurvInnhold = (List<HKurv>)Session["KurvInnhold"];
DataClasses1DataContext db = new DataClasses1DataContext();
if (Session["KurvInnhold"] != null)
{
var query = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
d.VareKjøpt.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
BestiltAntall = d.AntallValgt,
Price = b.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query;
Handlekurv1.DataBind();
}
But it does not allow for usage of db and list<> in same query
Solved! Modified magnus's answer
var kjopKollonne = from p in KurvInnhold
select p.VareKjøpt;
var query1 = (from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
where
kjopKollonne.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}).ToList();
var query2 = from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();
Try this:
var query1 = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
KurvInnhold.Select(k => k.VareKjøpt).Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}.ToList();
var query2 =
from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();

Categories