AND between multiple form clauses - c#

I have this viewModel
var viewModel = from c in _context.Companies
join co in _context.Component on c.id equals co.company_id
select new Joincco { Companies = c, Component = co} ;
and another model:
from check in _context.Companies
where
check.company_type.Contains(checkedBoxes[.....]) ||
check.company_type.Contains(....) ||
check.company_type.Contains(....)
select new Joincco { Companies = check }
I need a new view that can provide AND between them.
I need to get company_types from Companies that contains specific values and some properties equals a specific value from component.How can I do that?

Used intersect
return View(deneme.Intersect(longlinq).OrderBy(m => m.Companies.company_name));

Related

Implement ASP.NET MVC5 search functionality using 2 tables

I have created two tables: Claim and ClaimAttachments.
I'm trying to join them on ClaimID in order to get the filtered data from both the tables.
public ActionResult Index(int? search)
{
if (search!=null)
{
var Product = (from P in db.Claims
join C in db.ClaimAttachments on
P.ClaimID equals C.ClaimID
select new Claim
{
ClaimID = P.ClaimID,
ClaimBatchID = P.ClaimBatchID,
PatientControlNumber = P.PatientControlNumber,
PatientFirstName = P.PatientFirstName,
PatientLastName = P.PatientLastName,
ServiceFromDate = P.ServiceFromDate,
ServiceToDate = P.ServiceToDate,
});
return View(db.Claims.Where(x => x.ClaimID == search).ToList());
}
else
{
return View(db.Claims.ToList());
}
I'm able to get the searched result but from single table. The join is not working.
Currently you're only selecting from the Claims data:
return View(db.Claims.Where(x => x.ClaimID == search).ToList());
You have a join query just above that line of code:
var Product = (from P in db.Claims
join C in db.ClaimAttachments on
P.ClaimID equals C.ClaimID
select new Claim
{
ClaimID = P.ClaimID,
ClaimBatchID = P.ClaimBatchID,
PatientControlNumber = P.PatientControlNumber,
PatientFirstName = P.PatientFirstName,
PatientLastName = P.PatientLastName,
ServiceFromDate = P.ServiceFromDate,
ServiceToDate = P.ServiceToDate
});
But you don't do anything with the results of that query. It sounds like you meant to use the results of that query (which is in the Product variable, which incidentally should probably have a plural name since it's a collection) instead of just selecting from db.Claims. Something like this:
return View(Product.Where(x => x.ClaimID == search).ToList());
Note however that you're still only selecting data from one table. Though the join operation may alter the results of that selection. But the selection itself is here:
select new Claim
{
ClaimID = P.ClaimID,
ClaimBatchID = P.ClaimBatchID,
PatientControlNumber = P.PatientControlNumber,
PatientFirstName = P.PatientFirstName,
PatientLastName = P.PatientLastName,
ServiceFromDate = P.ServiceFromDate,
ServiceToDate = P.ServiceToDate
}
Notice how every value selected is from the P alias, which is defined here:
from P in db.Claims
So you're successfully joining the two tables, but only selecting data from one of the two tables. If you want to also select data from the other table then, well, you need to select data from the other table. For example, if there's a property on that table called SomeProperty that you want to select then you'd need to select it, and into an object which has that property.
For example, you might create a view model (let's call it ClaimViewModel as an example) which represents a combined record of the two tables, containing the properties you want from each. Then you'd select into that type:
select new ClaimViewModel
{
ClaimID = P.ClaimID,
ClaimBatchID = P.ClaimBatchID,
PatientControlNumber = P.PatientControlNumber,
PatientFirstName = P.PatientFirstName,
PatientLastName = P.PatientLastName,
ServiceFromDate = P.ServiceFromDate,
ServiceToDate = P.ServiceToDate,
SomeProperty = C.SomeProperty // <--- here
}
This would select the combined data into a list of ClaimViewModel objects, which you'd then filter based on your "search" and return to your view just like you do with the Claims objects now. And of course that view would need to be updated to expect a collection of ClaimViewModel objects instead of a collection of Claim objects.

Select a records as list and parsing to the view

I want to select some data from the database and pass to the view as a list. Because Same selected data may have one or more records. So I wrote this code to select the data I wanted.
{
int CurrDepId = (from e in db.CreateEmployee where e.Id == UsrIDT select new { e.Id }).First().Id;
int CostCenterId = (from c in db.CreateDepartment where c.Id == CurrDepId select new { c.Cost_Center_Id }).First().Cost_Center_Id;
var RelatedRequests = (from a in db.AppRequest
join e in db.CreateEmployee on a.Create_By equals e.Id
join d in db.CreateDepartment on e.DepId equals d.Id
join c in db.PaymentVoucher on a.Id equals c.Req_Id
join p in db.PaymentVoucherExpenDetails on d.Cost_Center_Id equals p.CostCenterId
where e.DepId != CurrDepId && p.CostCenterId == CostCenterId
select new
{
e.EmpName, //string value
a.Created_Date.ToString(), //string value
d.Department,//string value
a.Id,//int value
e.UserImage // byte value
}).ToList();
}
Session["NewsFeed"] = RelatedRequests;
And then I passed it to the session.
In the session I called the list as this
List<SelectListItem> Newsfeed = Session["NewsFeed"] as List<SelectListItem>;
But when debugging In the RelatedRequests shows there are 4 list. But in the view, Newsfeed returns null. Can you guide me which part I code it wrong. Thank you.
I have sorted it myself.
I created a view model and pass the data to the viewmodel. Then from the view I called to that viewmodel and got the records.

retrieving nested collections with LINQ to SQL

I'm trying to get back a list of TransferIds, for each transfer a list of ChargeIds, and for each of those a list of ReferralMatches
here is what I've got
(from c in Commissions
where c.TransferStatus == "Paid"
where c.AdminHasReleased == false
join r in ReferralMatches on c.ReferralMatchId equals r.ReferralMatchId
group c by new { c.TransferId } into grp
select new {
TransferId = grp.Key.TransferId,
Charges = from c in grp
group c by c.ChargeId into grp2
select new {
ChargeId = grp2.Key,
Referrals = grp2 }
})
This works and is very close. It pulls back something that looks like this:
This looks like Charges that belong to a TransferId but what I need is ReferralMatches that belong to Charges that belong to a transferId. I've tried another select to pull in 'r' but running into errors.
I think LINQ people will be able to gather what they need from this post but if more info is needed, kindly let me know. Thank you.
EDIT, adding table samples
The two expanded tables are what I have to work with. It probably isn't useful but keep in mind that the ReferralMatch table also has ChargeId. One chargeId can cover multiple ReferralMatches but once the funds are available a bank transfer occurs...when that happens, records are created in the Commissions table.
So what I'm looking for is a list of TransferIds, foreach Id a list of chargeIds, and foreach chargeId a list of ReferralMatches...the innermost list of ReferralMatches would be full records from that table.
EDIT, more attempts
here's my latest attempt
from c in Commissions
where c.TransferStatus == "paid"
group c by c.TransferId into transferGroup
select new {
TransferId = transferGroup.Key,
Charges = from c in transferGroup
join r in ReferralMatches on c.ReferralMatchId equals r.ReferralMatchId
group c by c.ChargeId into chargeGroup
select new {
ChargeId = chargeGroup.Key,
Referrals = from r in chargeGroup
select new {
Referral = r
}
}
}
which pulls up something like this:
but unless I'm reading this incorrectly, the innermost item is still commission table which doesn't make sense. I need that to be ReferralMatches that have a ChargeId of [whatever]
You might need to separate out the expression into two and pull through the Referrals in the first expression, and then group on a second expression as follows:
var commissionAndReferrals =
from c in Commissions
where c.TransferStatus == "Paid"
where c.AdminHasReleased == false
join r in ReferralMatches on c.ReferralMatchId equals r.ReferralMatchId
select new { Commisson = c, Referral = r };
var result =
from cAndR in commissionAndReferrals
group cAndR by cAndR.Commisson.TransferId into transferGroup
select new
{
TransferId = transferGroup.Key,
Charges = from c in transferGroup
group c by c.Commisson.ChargeId into chargeGroup
select new
{
ChargeId = chargeGroup.Key,
Referrals = chargeGroup.Select(x => x.Referral)
}
};

Can I put this in separate class?

I have this repetitive piece of code:
var expCodes = (from cpdet in _dataContextOrders.CodeProfileDetails
join cpd in _dataContextOrders.CodeProfileDefinitions on cpdet.CodeProfileDefinitionID equals cpd.ID
join cp in _dataContextOrders.CodeProfiles on cpd.CodeProfileID equals cp.ID
join cc in _dataContextOrders.FMSCostCentres on cpdet.CostCentreID equals cc.ID
join ec in _dataContextOrders.FMSExpenseCodes on cpdet.ExpenseCodeID equals ec.ID
where cp.ID == Convert.ToInt32(intCostCodeProfileId)
&& cpdet.CostCentreID == Convert.ToInt32(intCostCentreSelected)
&& ec.Active == true
select new
{
ec.ID,
ec.CostCentreID,
ExpenseCodeExternalRef = ec.ExternalRef,
ExpenseCodeDescription = ec.Description,
displayExpenseCode = ec.ExternalRef + " " + ec.Description
}).Distinct().OrderBy(ec => ec.displayExpenseCode);
ddlExpCode1.DataSource = expCodes;
ddlExpCode1.DataTextField = "displayExpenseCode";
ddlExpCode1.DataValueField = "ID";
What I would like to do is to put it into a Class on its own, as we did before LinqToSql, that I can call from my aspx.cs page, using the 2 parameters, intCostCodeProfileId and intCostCodeProfileId and it will return the data for the Drop Down List.
How can I do this?
You have to create a model class that matches the properties in your select statement (ID, CostCentreId etc.). Then modify the select new { to select new FreshlyCreatedModelClass() {.
The only way to return an anonymous type from your method is to use either IEnumerable<object> or IEnumerable<dynamic> neither which should be recommended in this scenario. Your method should return IEnumerable<FreshlyCreatedModelClass> (or IQueryable<FreshlyCreatedModelClass> could be used if you need to build the query further).
After you have sorted the model class, you can simply move the code to a separate method.
Create a normal class (e.g. Connection.cs) and add some code like this:
public class MyDataSourceReturner
{
public static Object retDatasource(Object _dataContextOrders, int intCostCodeProfileId){
var expCodes = (from cpdet in _dataContextOrders.CodeProfileDetails
join cpd in _dataContextOrders.CodeProfileDefinitions on cpdet.CodeProfileDefinitionID equals cpd.ID
join cp in _dataContextOrders.CodeProfiles on cpd.CodeProfileID equals cp.ID
join cc in _dataContextOrders.FMSCostCentres on cpdet.CostCentreID equals cc.ID
join ec in _dataContextOrders.FMSExpenseCodes on cpdet.ExpenseCodeID equals ec.ID
where cp.ID == Convert.ToInt32(intCostCodeProfileId)
&& cpdet.CostCentreID == Convert.ToInt32(intCostCentreSelected)
&& ec.Active == true
select new
{
ec.ID,
ec.CostCentreID,
ExpenseCodeExternalRef = ec.ExternalRef,
ExpenseCodeDescription = ec.Description,
displayExpenseCode = ec.ExternalRef + " " + ec.Description
}).Distinct().OrderBy(ec => ec.displayExpenseCode);
return expCodes;
}
}
Afterwards you can use this code like this:
ddlExpCode1.DataSource = MyDataSourceReturner.retDatasource(_dataContextOrders, 5);
and receive your DataSource.

dynamic linq group by clause

I have multiple linq queries that retrieve the same data just at different grouping levels. (potentially 3 different levels). The linq query currently results in an enumerable list of a custom object. The items I don't understand or wonder if possible (to reduce redundant code):
can I make the following group by clause to be dynamic?
if so, can it dynamically populate my custom object group data when it is grouped at that level.
For instance:
var myReport_GroupProductLevel =
from r in mySum_GroupProductLevel
join pc in _myPlotCount on r.Strata equals pc.Strata
join acr in _myStrataAcres on pc.Strata equals acr.Strata
group new { r, pc, acr } by new { r.Strata, pc.Count, acr.Acres, r.GroupName, r.ProductName } into g
select new DataSummary
{
Strata = g.Key.Strata,
PlotCount = g.Key.Count,
Acres = g.Key.Acres,
ClassName = string.Empty,
GroupName = g.Key.GroupName,
ProductName = g.Key.ProductName,
TPAMEAN = g.Sum(x => x.r.TPA / x.pc.Count),
TPADEV = g.Select(x => x.r.TPA).StdDev(g.Key.Count)
};
If I wanted to group only by "GroupName" instead... I would rewrite the query. Issues I see are, if I'm grouping by a value then I need that value in the query (g.Key.GroupName); but since I'm creating a new custom object the other non-grouped values such as "ClassName" require a value (I used string.Empty above, but that is static).
Thanks for any insight...
if anyone was curious, I got it to work by using a conditional statement... since grouping by empty will make it collapse.
var mySum_ClassGroupProductLevel =
from s in ReportData.myStands
join p in ReportData.myPlots on s.ID equals p.StandID
join t in ReportData.myTrees on p.ID equals t.PlotID
group t by new { s.Strata, p.ID,
ClassName = useClassName ? t.ClassName : string.Empty,
GroupName = useGroupName ? t.GroupName : string.Empty,
ProductName = useProductName ? t.ProductName : string.Empty }
into g
select new
{}

Categories

Resources