I have to include both the newest Note and Comment with view model that I am passing to my list view but I cannot figure out how to include it in the view model.
I tried to do include but after I type p it will not give me a list of my properties for MinimumProductInfo which ProductNotes is a property for it.
Here is the controller code I am trying:
public ActionResult MinimumProductInfoList()
{
var Model = _minimumProductInfo.GetAll();
var Notes = db.ProductNotes.Where(p => p.NoteTypeFlag == "p").OrderByDescending(p => p.NoteDate).First();
var Comments = db.ProductNotes.Where(p => p.NoteTypeFlag == "c").OrderByDescending(p => p.NoteDate).First();
var Model = db.MinimumProductInfo.Include(p => p)
var ViewModel = Model.Select(x => new ProductInfoWithNoteList { MinimumProductInfoID = x.MinimumProductInfoID, ItemCode = x.ItemCode, MinimumOnHandQuantity = x.MinimumOnHandQuantity, MaximumOHandQuantity = x.MaximumOHandQuantity, MinimumOrderQuantity = x.MinimumOrderQuantity, LeadTimeInWeeks = x.LeadTimeInWeeks });
return View(ViewModel);
}
Everything else is working except now I need to include the latest note and latest comment in to my viewmodel
This is what I have now with WithMetta's help:
public ActionResult MinimumProductInfoList()
{
var productInfoViewModelCollection =
from x in db.MinimumProductInfo
let pnote =
(from inner_pnote in db.ProductNotes
where x.MinimumProductInfoID == inner_pnote.MinimumProductInfoID
&& inner_pnote.NoteTypeFlag == "p"
orderby inner_pnote.NoteDate
select inner_pnote).FirstOrDefault()
let cnote =
(from inner_cnote in db.ProductNotes
where x.MinimumProductInfoID == inner_cnote.MinimumProductInfoID
&& inner_cnote.NoteTypeFlag == "c"
orderby inner_cnote.NoteDate
select inner_cnote).FirstOrDefault()
select new ProductInfoWithNoteList
{
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Comment = cnote.ToString(),
PermanentNote = pnote.ToString()
};
return View(productInfoViewModelCollection);
}
Maybe something like this using LINQ.
var productInfoViewModelCollection =
from x in db.MinimumProductInfo
where x != null
let pnote =
(from inner_pnote in db.ProductNotes
where inner_pnote != null
&& x.MinimumProductInfoID == inner_pnote.MinimumProductInfoID
&& inner_pnote.NoteTypeFlag == "p"
orderby inner_pnote.NoteDate descending
select inner_pnote).FirstOrDefault()
let cnote =
(from inner_cnote db.ProductNotes
where inner_cnote != null
&& x.MinimumProductInfoID == inner_cnote.MinimumProductInfoID
&& inner_cnote.NoteTypeFlag == "c"
orderby inner_cnote.NoteDate descending
select inner_cnote).FirstOrDefault()
select new ProductInfoWithNoteList {
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Comment = cnote,
PermanentNote = pnote
};
Related
I need help please!
When I perform the following LINQ query, it works perfectly (shows results)
using (var db = new MyEntities())
{
var result = (from dc in db.ClassDiary
where dc.DesTurm == dataForm.DesTurma
&& dc.Module == dataForm.Module
&& dc.CodDisc == dataForm.CdDisc
orderby dc.NrDiary
select new ClassDiaryMod
{
Id = dc.ID,
NrDiary = dc.NrDiary,
NrStudant = dc.NrStudant,
DesTurma = dc.DesTurma,
CdDisc = dc.CodDisc,
CdTeac = dc.CodTeac,
TotalFoult = (from f in db.Foult
where
f.NrStudant == dc.NrStudant &&
f.Disc == dc.CodDisc
select new FoultMod
{
Foults = f.Foult
}).Sum(x => x.Foults)
}).ToList();
return result;
When I try to apply the left join with multiple key does not display results
using (var db = new FamespEntities())
{
var result = (from dc in db.ClassDiary
join fn in db.Foult
on new { dc.NrStudant, dc.CodDisc, dc.DesTurm }
equals new { fn.NrStudant, CodDisc = fn.Disc, DesTurm = fn.Desturm } into fn_join
from fn in fn_join.DefaultIfEmpty()
where dc.DesTurm == dataForm.DesTurm
&& dc.Module == dataForm.Module
&& dc.CodDisc == dataForm.CdDisc
orderby dc.NroDiary
select new ClassDiaryMod
{
Id = dc.Id,
NrDiary = dc.NroDiary,
NrStudant = dc.NrStudant,
DesTurm = dc.DesTurm,
CdDisc = dc.CodDisc,
CdTeac = dc.CodTeac,
FoultOfDay = fn.Foult,
TotalFoults = (from f in db.Foult
where
f.NrStudent == dc.NrStudant &&
f.Disc == dc.CodDisc
select new FoultMod
{
Foults = f.Foult
}).Sum(x => x.Foults)
}).ToList();
Like to understand why the first code works and the second does not.
Thank you so much
Your equals
on new { dc.NrStudant, dc.CodDisc, dc.DesTurm }
equals new { fn.NrStudant, CodDisc = fn.Disc, DesTurm = fn.Desturm }
Is not correct, it should be
on new { NrStudant = dc.NrStudant, CodDisc = dc.CodDisc, DesTurm = dc.DesTurm }
equals new { NrStudant = fn.NrStudant, CodDisc = fn.Disc, DesTurm = fn.Desturm }
so field comparison could work.
I'm returning anonymouse type from my webapi controller, one of the values I need to be computed by using function. When I'm trying to do this way getting error say "Several actions were found that match request".
Here is how I call GET:
// GET api/Grafik/5
public IHttpActionResult GetGrafik(int id)
{
xTourist t = db.xTourist.Find(id);
var beach = db.xAdres.Find(t.Hotel).Kod;
var result = from a in db.Grafik
join b in db.Excursions on a.Excursion equals b.Kod
join c in db.Dates on a.KodD equals c.KodD
join d in db.Staff on a.Guide equals d.Kod
where c.Date > t.ArrDate && c.Дата < t.DepDate
let pu = from x in db.xPickUp where x.KodP == beach && x.Excursion == b.Kod select x.PickUpTime
orderby c.Date
select new { kodg = a.Kodg, excursion = b.Name, guide = d.GuideName, data = c.Date, pricead = b.Price,
pricech = b.PriceChd, pax = t.Pax, child = t.Ch, paxleft = GetPax(a.Kodg), pickup = pu.FirstOrDefault()};
return Ok(result);
}
And here is the function returning needed value:
public int GetPax(int id)
{
//get pax quota
var pre = db.Grafik.Where(k => k.Kodg == id).Select(p => p.Quota).SingleOrDefault();
if (pre.HasValue && pre.Value > 0)
{
//Get taken pax
var p = (from a in db.Orders where a.Kodg == id & !(a.Cansel == true) select a.Child).Sum();
var c = (from a in db.Orders where a.Kodg == id & !(a.Cansel == true) select a.Pax).Sum();
if (p.HasValue & c.HasValue)
{
return pre.Value - (p.Value + c.Value);
}
else
{
return pre.Value;
}
}
else
{
return 0;
}
}
Web API is seeing two public methods with id as a parameter and it can't figure out which one to execute when you send your request. Looking at your code, there's no need for the helper method GetPax() to be public. Try changing it to private.
private int GetPax(int id) // ...
I found solution. Ok, this could be a bit strange way, but it's working.
public IHttpActionResult GetГрафик(int id)
{
xTourist t = db.xTourist.Find(id);
var beach = db.xAdres.Find(t.Hotel).Kod;
var result = from a in db.Grafik
join b in db.Excursions on a.Excursion equals b.Kod
join c in db.Dates on a.Kodd equals c.Kodd
join d in db.Staff on a.Guidename equals d.Kod
join e in db.Заказы on a.КодГ equals e.КодГ
where c.Дата > t.Датапр && c.Дата < t.Датаотл
let pu = from x in db.xPickUp where x.КодП == beach && x.Excursion == b.Kod select x.PickUpTime
orderby c.Дата
let pl = a.Пребукинг - (e.Child + e.Pax)
select new { kodg = a.КодГ, excursion = b.Название, guide = d.Name, data = c.Дата, pricead = b.Price,
pricech = b.PriceChd, pax = t.Колчел, child = t.Дети, paxleft = pl, pickup = pu.FirstOrDefault()};
return Ok(result);
}
I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.
Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();
Take a look at my code here:
public static ItemType GetItem(int id)
{
ItemType it = new ItemType();
using (var context = matrix2.matrix2core.DataAccess.Connection.GetContext())
{
var q = (from ci in context.Item
where ci.ID == id
let TemplateID = ci.TemplateID
let Groups = from x in context.CriteriaGroup
where x.TemplateID == TemplateID
select new
{
x
}
let CriteriaItems = from x in context.CriteriaItem
where Groups.Select(y => y.x.ID).Contains(x.CriteriaGroupID)
select new
{
x
}
select new
{
ci.ID,
ci.Name,
ci.CategoryID,
ci.Description,
ci.ItemValue,
TemplateID,
Groups,
CriteriaItems,
ItemValues = from x in context.ItemValue
where x.ItemID == id
select new
{
x,
CriteriaID = x.CriteriaItem.Criteria.ID
}
}).FirstOrDefault();
if (q != null)
{
it.ID = q.ID;
it.CategoryID = q.CategoryID;
it.Name = q.Name;
it.TemplateID = q.TemplateID;
it.Description = q.Description;
it.CriteriaGroups = new List<CriteriaGroupType>();
it.CriteriaItems = new List<CriteriaItemType>();
it.ItemValues = new List<ItemValueType>();
foreach (var x in q.ItemValues)
{
ItemValueType ivt = new ItemValueType();
ivt.CriteriaItemID = x.x.CriteriaItemID;
ivt.CriteriaID = x.CriteriaID;
ivt.Data = x.x.Data;
ivt.ID = x.x.ID;
ivt.ItemID = x.x.ItemID;
it.ItemValues.Add(ivt);
}
/////////error when I added the orderby clause
foreach (var x in q.Groups.OrderBy(x => x.x.SortOrder))
{
CriteriaGroupType cgt = new CriteriaGroupType();
cgt.ID = x.x.ID;
cgt.Name = !string.IsNullOrEmpty(x.x.Name) ? x.x.Name : "Group" + x.x.ID;
cgt.SortOrder = x.x.SortOrder;
cgt.TemplateID = x.x.TemplateID;
it.CriteriaGroups.Add(cgt);
}
/////////error when I added the orderby clause
foreach (var temp in q.CriteriaItems.OrderBy(x => x.x.SortOrder))
{
CriteriaItemType cit = new CriteriaItemType();
cit.ID = temp.x.ID;
cit.CriteriaGroupID = temp.x.CriteriaGroupID;
cit.GroupName = (temp.x.Name != null) ? temp.x.Name : "Group" + temp.x.ID;
cit.CriteriaID = temp.x.CriteriaID;
cit.CriteriaName = temp.x.Criteria.Name;
cit.Name = !string.IsNullOrEmpty(temp.x.Name) ? temp.x.Name : temp.x.Criteria.Name;
cit.Options = temp.x.Options;
it.CriteriaItems.Add(cit);
}
}
}
return it;
}
Instead of letting SQL handle the sorting (OrderBy) I wanted asp.net to do the sorting instead. I took the sorting out of the SQL linq query and put it on the foreach loop. When I did that I got the error. Is there a way to fix this?
You should be able to go from IQueryable to IEnumerable with a simple
var q2 = q.ToList();
What I meant of course was :
var groups = q.Groups.ToList();
I currently have the following:
public IEnumerable<News> NewsItems
{
get { return from s in News.All() where s.Description.Contains(SearchCriteria) || s.Summary.Contains(SearchCriteria) select s; }
}
The problem is I only need to return the one property that actually has the data as well as the Title property, something similar to.
return from s in News.All() where s.Description.Contains(SearchCriteria) || s.Summary.Contains(SearchCriteria) select new {Title = s.Title, Data = //Description or Summary containing the data
How do I determine which one contains the search query?
UPDATE: I have this but it obviously hits the DB 3 times
var FoundInSummary = News.All().Any(x => x.Summary.Contains(SearchCriteria));
var FoundInDesc = News.All().Any(x => x.Description.Contains(SearchCriteria));
IEnumerable<NewsEventSearchResults> result = null;
if ((FoundInSummary && FoundInDesc) || (FoundInSummary))
{
result = (from s in News.All() where s.Summary.Contains(SearchCriteria) select new NewsEventSearchResults { Title = s.Title, Data = s.Summary, ID = s.ID }).AsEnumerable();
}
else if (FoundInDesc)
{
result = (from s in News.All() where s.Description.Contains(SearchCriteria) select new NewsEventSearchResults { Title = s.Title, Data = s.Description, ID = s.ID }).AsEnumerable();
}
return result;
UPDATE 2: Is this more efficent?
var ss = (from s in News.All() where s.Description.Contains(SearchCriteria) || s.Summary.Contains(SearchCriteria) select s).ToList();
List<NewsEventSearchResults> resultList = new List<NewsEventSearchResults>();
foreach (var item in ss)
{
bool FoundInSummary = item.Summary.Contains(SearchCriteria);
bool FoundInDesc = item.Description.Contains(SearchCriteria);
if ((FoundInSummary && FoundInDesc) || (FoundInSummary))
{
resultList.Add(new NewsEventSearchResults { Title = item.Title, Data = item.Summary, ID = item.ID });
}
else if (FoundInDesc)
{
resultList.Add(new NewsEventSearchResults { Title = item.Title, Data = item.Description, ID = item.ID });
}
}
What if they both contain the criteria? Or are they mutually exclusive? If so
Data = (s.Description != null ? s.Description : s.Summary)
I went with option 3