I am newish to linq and get this error everytime I do this join. One of the fields I'm joining on is nullable.
try
{
DCEDataContext dc = new DCEDataContext();
List<Account> AcctWithChild=new List<Account>();
AcctWithChild.Add(Account.GetById(3));
//var query = (from acct in AcctWithChild
List<CTRAC.WebApi.Models.Organization> Organizations = (from acct in AcctWithChild
join allOrg in dc.Organizations on acct.ID equals allOrg.AccountID
join allEngage in dc.Engagements on allOrg.in_id equals allEngage.OrganizationID
join allEngageForm in dc.EngagementForms on allEngage.ID equals allEngageForm.EngagementID
join allEnFormSub in dc.EngagementFormFilingSubmissions on allEngageForm.ID equals allEnFormSub.EngagementFormID
into EngagementFormFilingSubGroup
from allEnFormSub in EngagementFormFilingSubGroup.DefaultIfEmpty()
where allOrg.AccountID.HasValue
select new CTRAC.WebApi.Models.Organization { Name = allOrg.vc_BusinessName, OrganizationID = allOrg.OrganizationId,Return990_Id=allEngageForm.ID, EfileSubmissionDate=allEnFormSub.Timestamp }).Take(100).ToList();
edit When I make EfileSubmisionDate=null It goes through but setting it to allEnFormSub.Times which is sumtimes null gives me an error.
May be using HasValue
List<CTRAC.WebApi.Models.Organization> Organizations = (from acct in AcctWithChild
join allOrg in dc.Organizations on acct.ID equals allOrg.AccountID??0
let MYID=allOrg.Field<Int?>("AccountID")
where MYID.HasValue
select new CTRAC.WebApi.Models.Organization { Name = allOrg.vc_BusinessName, OrganizationID = allOrg.OrganizationId,Return990_Id=5, EfileSubmissionDate=acct.TrialBegin.Value }).ToList();
Related
In my asp.net MVC application, view model I have created a property type string to display date.
But in the model, the property is stored as DateTime, so in my query, I have assigned the DateTime by converting it to ToShortDateString.
Because the value stored is with the DateTime in the table.(example2022-10-06 11:32:48.917)
But in the view, I just want to show the Date only.
When running this query I got this error
LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method,
and this method cannot be translated into a store expression.'
Just want to know how to pass only the date to the view of this kind of query.
This is my current code.
var TaskMain = (from t in db.TaskMain
join service in db.Services on t.Service_Id equals service.Id
join category in db.ServiceCategory on service.Service_Category_Id equals category.Id
join branch in db.Branch on t.Current_Branch_Id equals branch.Id
join emp in db.Employee on t.Task_Assigned_Emp_Id equals emp.Id
where t.Id == id
select new TaskDetails
{
Id = t.Id,
Note = t.Note,
Current_Step= t.Task_Step_Id,
Service_Category = category.Service_Category_Name,
Service_End_Date = t.Service_End_Date.ToShortDateString(),
Service_Price = t.Service_Price,
Service_Start_Date = t.CreatedDate.ToShortDateString(),
Task_Created_Branch = branch.BranchName,
Service_Name = service.Service_NameEng
}).ToList();
ToShortDateString() is not something that the database recognize. So you need to bring the conversion to client side by using .AsEnumerable() (or .ToList()). Try this code.
var TaskMain = (from t in db.TaskMain
join service in db.Services on t.Service_Id equals service.Id
join category in db.ServiceCategory on service.Service_Category_Id equals category.Id
join branch in db.Branch on t.Current_Branch_Id equals branch.Id
join emp in db.Employee on t.Task_Assigned_Emp_Id equals emp.Id
where t.Id == id
select new
{
Id = t.Id,
Note = t.Note,
Task_Step_Id= t.Task_Step_Id,
Service_Category_Name = category.Service_Category_Name,
Service_End_Date = t.Service_End_Date,
Service_Price = t.Service_Price,
CreatedDate = t.CreatedDate,
BranchName = branch.BranchName,
Service_NameEng = service.Service_NameEng
}).AsEnumerable()
.Select(t => new TaskDetails
{
Id = t.Id,
Note = t.Note,
Current_Step= t.Task_Step_Id,
Service_Category = t.Service_Category_Name,
Service_End_Date = t.Service_End_Date.ToShortDateString(),
Service_Price = t.Service_Price,
Service_Start_Date = t.CreatedDate.ToShortDateString(),
Task_Created_Branch = t.BranchName,
Service_Name = t.Service_NameEng
}).ToList();
I'm currently having a rough time converting my SQL query to LINQ for a school project I'm using WPF and Entity Framework
here is my SQL query (working exactly as I expect)
select IngrediantName,sum(IngrediantQuantity) as Quantity, IngrediantMeasurementUnit from Users
join Shopping_List
on Users.UserID = Shopping_List.ShoppingListID
join List_Item
on List_Item.ShoppingListID = Shopping_List.ShoppingListID
join Ingrediant
on Ingrediant.IngrediantID = List_Item.IngrediantID
where Users.UserID = 1
group by IngrediantName,IngrediantMeasurementUnit
Here is the query that I have so far
var query = from user in dbContext.Users
join shoppingList in dbContext.ShoppingLists on user.UserId equals shoppingList.UserId
join listItem in dbContext.ListItems on shoppingList.ShoppingListId equals listItem.ShoppingListId
join ingrediant in dbContext.Ingrediants on listItem.IngrediantId equals ingrediant.IngrediantId
where currentUserNumber == user.UserId
select new
{
name = ingrediant.IngrediantName,
quantity = ingrediant.IngrediantQuantity,
unit = ingrediant.IngrediantMeasurementUnit,
};
Here is what i try so far
var query = from user in dbContext.Users
join shoppingList in dbContext.ShoppingLists on user.UserId equals shoppingList.UserId
join listItem in dbContext.ListItems on shoppingList.ShoppingListId equals listItem.ShoppingListId
join ingrediant in dbContext.Ingrediants on listItem.IngrediantId equals ingrediant.IngrediantId
where currentUserNumber == user.UserId
group ingrediant by ingrediant.IngrediantQuantity into x
select new
{
name = x.GroupBy(x => x.IngrediantName),
quantity = x.Sum(x => x.IngrediantQuantity),
unit = x.GroupBy(x => x.IngrediantMeasurementUnit),
};
this one return the following error wiches doesn't tell much
Argument type 'System.Linq.IQueryable1[System.Linq.IGrouping2[System.String,Microsoft.EntityFrameworkCore.Query.TransparentIdentifierFactory+TransparentIdentifier2[Microsoft.EntityFrameworkCore.Query.TransparentIdentifierFactory+TransparentIdentifier2
If someone could point me in the right direction I would appreciate it, if you need more info I will provide it for sure
Thanks
UPDATE
I got this working here the answers to the question for anyone else
var query =
from user in dbContext.Users
join shoppingList in dbContext.ShoppingLists
on user.UserId equals shoppingList.UserId
join listItem in dbContext.ListItems
on shoppingList.ShoppingListId equals listItem.ShoppingListId
join ingrediant in dbContext.Ingrediants
on listItem.IngrediantId equals ingrediant.IngrediantId
where currentUserNumber == user.UserId
group ingrediant by new { name = ingrediant.IngrediantName, unit = ingrediant.IngrediantMeasurementUnit } into x
select new
{
name = x.Key.name,
quantity = x.Sum(x => x.IngrediantQuantity),
unit = x.Key.unit,
};
if you look at the group line
group ingrediant by new { name = ingrediant.IngrediantName, unit = ingrediant.IngrediantMeasurementUnit } into x
from my understanding you use the new to create a new selector then you can use x.key.name and x.key.unit where name and unit are simply some variable
I am not able to work with the below join.
Idea is to find any new (AumProductId and IdClient) combinations from AceBiMonthlyDaos to create entry in Investment table with Unique Id, if those AumProductId and IdClient exist in Reference table of Instrument and Financial Account respectively.
var result = (from AceBi in context.AceBiMonthlyDaos
join Inst in context.Instruments
on AceBi.AumProductId equals Inst.AceId
join FinAcct in context.FinancialAccounts
on AceBi.IdClient equals FinAcct.AceClientId
join Invst in context.Investments
on new { Inst.Id, FinAcct.Id } equals { Invst.InstrumentId, Invst.FinaAcctId} into pair
from InvestmentDao in pair.DefaultIfEmpty()
var query = (from AceBi in context.AceBiMonthlyDaos
join Inst in context.Instruments on AceBi.AumProductId equals Inst.AceId
join FinAcct in context.FinancialAccounts on AceBi.IdClient equals FinAcct.AceClientId
join Invst in context.Investments on new { instrumentId = Inst.Id, finAccountId = FinAcct.Id } equals new { instrumentId = Invst.InstrumentId, finAccountId = Invst.FinAcctId }
into pair
from Invst in pair.DefaultIfEmpty()
select new { Inst, FinAcct, Invst }).Distinct();
So I have a SQL view that I've created that provides me what I need. Essentially it's a job position billeting system that shows how many positions have been authorized vs filled (or assigned).
SELECT Companies.Name AS Company, Grades.Name AS Grade, Series.Name
AS Series, Positions.Authorized, COUNT(People.PersonId) AS Assigned
FROM Companies INNER JOIN
Positions ON Companies.Id = Positions.CompanyId INNER JOIN
Series ON Positions.SeriesId = Series.Id INNER JOIN
Grades ON Positions.GradeId = Grades.Id INNER JOIN
People ON Positions.CompanyId = People.CompanyId AND
Positions.SeriesId = People.SeriesId AND Positions.GradeId = People.GradeId
GROUP BY Companies.Name, Grades.Name, Series.Name, Positions.Authorized
Now what I'd like to be able to do is recreate this in a LINQ query. I've almost got it where I need it; however, I can't figure out how to add the counted column at the end that's based on the People table.
Here's my current LINQ query:
var query = from a in db.Companies
join b in db.Positions on a.Id equals b.CompanyId
join c in db.Series on b.SeriesId equals c.Id
join d in db.Grades on b.GradeId equals d.Id
join e in db.People on new { b.CompanyId, b.SeriesId, b.GradeId } equals new { e.CompanyId, e.SeriesId, e.GradeId }
group a by new { CompanyName = a.Name, GradeName = d.Name, SeriesName = c.Name, b.Authorized, e.PersonId } into f
select new { Company = f.Key.CompanyName, Grade = f.Key.GradeName, Series = f.Key.SeriesName, f.Key.Authorized, Assigned = /* needs to be Count(People.PersonId) based on last join */ )};
Thanks in advance for any help you can provide!
Figured it out. The reason why it was posting multiple rows and not doing a proper count on the same row was because in my "group by" I added in "e.PersonId" when it should have simply been removed. I also had to add a few things to make it work on the front-end razor views since it's an anonymous type (this doesn't have anything to do with the original question, but thought I'd give reason to the changes). So the person who removed their answer, you were partially right, but the reason it wasn't working was because of the additional fieldin the group by:
dynamic query = (from a in db.Companies
join b in db.Positions on a.Id equals b.CompanyId
join c in db.Series on b.SeriesId equals c.Id
join d in db.Grades on b.GradeId equals d.Id
join e in db.People on new { b.CompanyId, b.SeriesId, b.GradeId } equals new { e.CompanyId, e.SeriesId, e.GradeId }
group a by new { CompanyName = a.Name, GradeName = d.Name, SeriesName = c.Name, b.Authorized } into f
select new { Company = f.Key.CompanyName, Grade = f.Key.GradeName, Series = f.Key.SeriesName, Authorized = f.Key.Authorized, Assigned = f.Count()}).AsEnumerable().Select(r => r.ToExpando());
And what it looks like on the page:
I am trying to write a query that grabs information from one database and joins it to information in a different database.
TableA
idA
valueA
idB
TableB
idB
valueB
The tricky part is that in TableA, idB isn't always defined, so when I do a normal join, I only get results where TableA has a idB value. What I want is to be able to grab all of the information from TableA even if it doesn't have a corresponding idB value.
Here is a query expression syntax version of the left join to follow up on tvanfosson's answer.
var query = from rowA in db.TableA
join rowB in db.TableB
on rowA.idB equals rowB.idB into b
from item in b.DefaultIfEmpty()
select new
{
idA = rowA.idA,
valueA = rowA.valueA,
idB = rowA.idB,
valueB = item != null ? item.valueB : 0 // or other default value
};
Use a left outer join by checking if the value returned from the right hand side is null and supplying a default value for that case.
var q = db.TableA.Join( db.TableA,
a => a.idB,
b => b.idB,
(a,b) => new
{
A = a.ValueA,
B = b == null ? null : b.ValueB
});
You can do a left outer join in LINQ with SelectMany (directly calling Queryable methods) or in comprehension syntax join ... into:
var results = from a in db.TableA
join b in db.TableB on a.idB equals b.idB
into found
select new {
A = a,
Bs = found
};
In the output Bs will be IEnumerable<typeof-db-TableB>
Left Join Example:
var leftOuterJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
from item in prodGroup.DefaultIfEmpty(new Product{Name = String.Empty, CategoryID = 0})
select new { CatName = category.Name, ProdName = item.Name };