how to display name use LINQ - asp.net-mvc

Actually i have two tables i want to display records of the use of second table. Please help me in this. Let me provide you example.
[TABLE1]
LocationID LoginID Location_Name
1 101 A
2 102 B
3 103 C
[TABLE2]
ID LoginID No_Of_Item Location ToLocation
1 101 5 1 2
2 102 6 2 3
3 103 7 1 3
This is my database. Now i want to show [TABLE2] records with location name. But i am unable to do that. Please help me in this LINQ Query.
This is my code.
public IQueryable<StockTransferViewModel> GetAllStockTransferDetailByLoginId(string LoginId)
{
var StockList = (from aspuser in context.AspNetUsers
join cus in context.Customers on aspuser.Id equals cus.LoginID
join transfer in context.StockTransfers on aspuser.Id equals transfer.LoginID
where transfer.LoginID == LoginId
select new StockTransferViewModel
{
ID = transfer.ID,
LoginID = transfer.LoginID,
Date_Of_Transfer = transfer.Date_Of_Transfer,
No_Of_Sku = transfer.No_Of_SKU,
FromLocationName=transfer.Location,
ToLocation=transfer.ToLocation,
}).AsQueryable();
return StockList;
}

If TABLE1 is named Locations, you'll likey want to add the following lines after the line starting with join transfer in:
join fromLocation in context.Locations on transfer.Location equals fromLocation.LocationID
join toLocation in context.Locations on transfer.Location equals toLocation.LocationID
Then in your select statement, you'll want:
FromLocationName = fromLocation.Location_Name,
ToLocation = toLocation.Location_Name,

Related

How to get Average rating in entity framework

Hi I have below code as
var query = (from R in db.Registrations
join c in db.Campus
on R.CampusId equals c.CampusId
from tsr in db.TutorStudentRequests.Where(t => t.TutorId == R.RegistrationId).DefaultIfEmpty()
where R.UserTypeId == 2 && tsr.StatusId!=3
orderby R.Name ascending
select new
{
RegistrationId = R.RegistrationId,
Name = R.Name,
Email = R.Email,
Phone = R.Phone,
Password = c.CampusName,
IsGPA = R.IsGPA,
IsActive = R.IsActive,
StripeId = R.StripeId,
CreatedOn = R.CreatedOn,
UserTypeId =tsr.StudentReviewRating
})
.ToList();
I have Registration table having single row and I also have another table TutorStudentRequests which have multiple rows. How can I get average of column name StudentReviewRating present in TutorStudentRequests table?
Structure may be seem as:
Registration Table
RegistrationId Name Email
1 abc abc#gmail.com
2 xyz xyz#gmail.com
TutorStudentRequests Table
Id TutorId(RegistrationId of F.k.) StudentReviewRating
1 1 5
2 1 2
3 1 1
4 2 3
I want UserTypeId data as average of StudentReviewRating for each TutorId
Tried
var query = (from R in db.Registrations
join c in db.Campus
on R.CampusId equals c.CampusId
from tsr in db.TutorStudentRequests.Where(t => t.TutorId == R.RegistrationId).DefaultIfEmpty()
where R.UserTypeId == 2 && tsr.StatusId != 3
group R by new
{
R.RegistrationId,
R.Name,
R.Email,
R.Phone,
c.CampusName,
R.IsGPA,
R.IsActive,
R.StripeId,
R.CreatedOn,
} into groupings
select new
{
RegistrationId = groupings.Key.RegistrationId,
Name = groupings.Key.Name,
Email = groupings.Key.Email,
Phone = groupings.Key.Phone,
Password = groupings.Key.CampusName,
IsGPA = groupings.Key.IsGPA,
IsActive = groupings.Key.IsActive,
StripeId = groupings.Key.StripeId,
CreatedOn = groupings.Key.CreatedOn,
Average = groupings.Average(p=>Convert.ToDecimal(p.StudentReviewRating))
});
But it is saying Registration does not contain a definition for 'StudentReviewRating'..
What is wrong?
how about grouping by tutor, calculate the average as total ratings/number of ratings
var query = from request in data
group request by request.TutorId into groupings
let total = groupings.Sum(p=>p.StudentReviewRating)
let number = groupings.Count()
let average = (decimal)total/number
select new
{
TutorId = groupings.Key,
Summary = new
{
Total = total,
Number = number,
Average = average
}
}
and results would look like this for the given test case
TutorId Summary
1 Total 8
Number 3
Average 2.66
2 Total 3
Number 1
Average 3
Edit extra joins and extended group by
var query = from registration in registrations
join request in requests
on registration.RegistrationId equals request.TutorId
group request by new
{
registration.RegistrationId,
registration.Name,
request.TutorId,
} into groupings
select new
{
RegistrationId = groupings.Key.RegistrationId,
TutorId = groupings.Key.TutorId,
Average = groupings.Average(p=>p.StudentReviewRating)
}
Hi you can Use this to have all you want about math here
https://numerics.mathdotnet.com/

Can I consolidate the results of my Linq to SQL query?

Can I consolidate my Linq to Sql query results as part of the query? For example the following query would return list A below. I want my list to be consolidated like list B below.
IEnumerable<JoinClass> points =
from c in db.Users2
join e in db.Categories on c.Id_Users2 equals e.FK_Users2
join f in db.Programs on e.Id_Category equals f.FK_Categories
join g in db.Points on f.Id_Programs equals g.FK_Programs
where c.EEID == UserEEIDCast
orderby g.EntryDate ascending
select new JoinClass
{
Category = e.Category,
Programs = f.Programs,
Points = g.Points,
EEID = c.EEID,
EntryDate = g.EntryDate,
Name = c.Name
return View(points);
List A
Name Program Points
Jim Running 10
Jim Running 3
Jim Walking 7
Jim Walking 4
Bob Running 2
Bob Running 1
List B
Name Program Points
Jim Running 13
Jim Walking 11
Bob Running 3
try:
points = points
.GroupBy(x => new { x.Name, x.Program } )
.Select(x => new JoinClass() {Name = x.Key.Name, Program = x.Key.Program, Points = x.Sum(y => y.Points) /* copy other properties to the new JoinClass here */ });
This code groups the result using a composite key (Name and Program), then for each group it creates a new JoinClass with Points equal to the sum of all the points in that group.

I want to union together four queries and set this to be the repeater's data source

Based on user design I have to union together four queries and put them in a repeater.
var qryIssuer = from l in dbRRSP.LOA
join lrb in dbRRSP.LOAOrReferredBy on l.LOAOrReferredById equals lrb.LoaOrReferredById
join lat in dbRRSP.LOAAccessType on l.LOAAccessTypeId equals lat.LOAAccessTypeId
join iss in dbRRSP.Issuer on l.IssuerId equals iss.IssuerId
where
l.PersonId == personId
select new
{
LOAOrReferredByDescription = lrb.LoaOrReferredByDescription,
lat.LOAAccessTypeDescription,
PersonType = "Issuer",
LOAName = iss.CompanyName,
l.DateAdded
};
var qryEMD = from l in dbRRSP.LOA
join lrb in dbRRSP.LOAOrReferredBy on l.LOAOrReferredById equals lrb.LoaOrReferredById
join lat in dbRRSP.LOAAccessType on l.LOAAccessTypeId equals lat.LOAAccessTypeId
join emd in dbRRSP.Agent on l.AgentId equals emd.AgentId
where
l.PersonId == personId
select new
{
LOAOrReferredByDescription = lrb.LoaOrReferredByDescription,
lat.LOAAccessTypeDescription,
PersonType = "EMD",
LOAName = emd.CompanyName,
l.DateAdded
};
var qryEmdRep = from l in dbRRSP.LOA
join lrb in dbRRSP.LOAOrReferredBy on l.LOAOrReferredById equals lrb.LoaOrReferredById
join lat in dbRRSP.LOAAccessType on l.LOAAccessTypeId equals lat.LOAAccessTypeId
join ar in dbRRSP.AgentRepresentative on l.EMDRepresentativeId equals ar.AgentRepresentativeId
join arp in dbRRSP.Person on ar.PersonId equals arp.PersonId
where
l.PersonId == personId
select new
{
LOAOrReferredByDescription = lrb.LoaOrReferredByDescription,
lat.LOAAccessTypeDescription,
PersonType = "EMD Rep",
LOAName = arp.FirstName + ' ' + arp.LastName, l.DateAdded
};
var qryLOAPerson = from l in dbRRSP.LOA
join lrb in dbRRSP.LOAOrReferredBy on l.LOAOrReferredById equals lrb.LoaOrReferredById
join lat in dbRRSP.LOAAccessType on l.LOAAccessTypeId equals lat.LOAAccessTypeId
join lp in dbRRSP.LOAPerson on l.LOAPersonId equals lp.LOAPersonId
where
l.PersonId == personId
select new
{
LOAOrReferredByDescription = lrb.LoaOrReferredByDescription, lat.LOAAccessTypeDescription,
PersonType = "Person",
LOAName = lp.LOAPersonName,
l.DateAdded
};
This is the four queries. And the trickiest part is that the last field is a datetime, which is causing me some issues. I know how to union two of them together like this:
var qryMultipleLOA = qryIssuer.Union(qryEMD).ToList().Select(loa => new ExtendedLOA
{
LOAOrReferredByDescription = loa.LOAOrReferredByDescription,
LOAAccessTypeDescription = loa.LOAAccessTypeDescription,
PersonType = loa.PersonType,
LOAName = loa.LOAName,
DateAdded = DateTime.Parse(loa.DateAdded.ToString()).ToString("MM/dd/yyyy")
});
But I'm at a loss on how to add the last two queries - first I tried wrapping it in brackets and adding a .Union which didn't work, and then when I tried to nest them with appropriate .ToLists, that didn't work either.
Below is the code to bind it to the repeater.
rptLOA.DataSource = qryMultipleLOA;
rptLOA.DataBind();
Suggestions would be greatly appreciated.
Did you try something like?
var qryMultipleLOA = qryIssuer.Union(qryEMD).Union(qryEmdRep).Union(qryLOAPerson).ToList();
Provided your queries' footprints are the same, this shouldn't be an issue to chain them upon each other.
Edit:
I would also recommend the following:
Create a class to hold an instance of the resultant data.
Instead of creating lists of dynamic variables generated from Linq and hoping they all match, funnel the linq results into a List. That way you can tell immediately if you have a type mismatch.
Once you have four lists of the same List, Unions as per my syntax above will be a snap.
Dynamic Linq lists can be a pain, unwieldy and a single property type change can throw of your code at runtime rather than design time. If you follow the steps above, your code will be much more maintainable and clear to you and others.
I hope this helps in some way.

get count from Iqueryable<T> in linq-to-sql?

The following code doesn't seem to get the correct count.....
var materials = consRepository.FindAllMaterials().AsQueryable();
int count = materials.Count();
Is it the way to do it.... Here is my repository which fetches records...
public IQueryable<MaterialsObj> FindAllMaterials()
{
var materials = from m in db.Materials
join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
where m.Is_Deleted == 0
select new MaterialsObj()
{
Id = Convert.ToInt64(m.Mat_id),
Mat_Name = m.Mat_Name,
Mes_Name = Mt.Name,
};
return materials;
}
Edit:
when i use this,
var materials = consRepository.FindAllMaterials().AsQueryable();
return View("Materials", materials);
I get 18 rows in my table... So y cant i get the count as 18 instead it gives 12
Ans:
Breakpoint doesn't seem produce me the result but response.Write(count) did...
This should get the correct count:
int count = consRepository.FindAllMaterials().Count();
How are you iterating through the model in your view?
Is it possible that you are displaying duplicate entries?
Is it possible that you're not joining on the correct columns? The only reason I ask is that your id columns aren't consistently named in each class. For Materials you are using Mat_id, but in MeasurementTypes you are using simply, Id. It makes me wonder if you're trying to join a natural key value against an artificial primary key instead of the corresponding natural foreign key.

Linq to Entity with multiple left outer joins

I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:
Company, CompanyProduct, Product
The CompanyProduct is linked to its two parent tables, Company and Product.
I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows:
SELECT * FROM Company AS C
LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID
LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID
WHERE P.ProductID = 14 OR P.ProductID IS NULL
My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables.
So how do you write the same kind of join in LINQ to Entity to acheive a similiar result?
I have tried a few different things but can't get the syntax correct.
Thanks.
Solved it!
Final Output:
theCompany.id: 1
theProduct.id: 14
theCompany.id: 2
theProduct.id: 14
theCompany.id: 3
Here is the Scenario
1 - The Database
--Company Table
CREATE TABLE [theCompany](
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
GO
--Products Table
CREATE TABLE [theProduct](
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED
( [id] ASC
) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
GO
--CompanyProduct Table
CREATE TABLE [dbo].[CompanyProduct](
[fk_company] [int] NOT NULL,
[fk_product] [int] NOT NULL
) ON [PRIMARY];
GO
ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT
[FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company])
REFERENCES [theCompany] ([id]);
GO
ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT
[FK_CompanyProduct_theCompany];
GO
ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT
[FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product])
REFERENCES [dbo].[theProduct] ([id]);
GO
ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT
[FK_CompanyProduct_theProduct];
2 - The Data
SELECT [id] ,[value] FROM theCompany
id value
----------- --------------------------------------------------
1 company1
2 company2
3 company3
SELECT [id] ,[value] FROM theProduct
id value
----------- --------------------------------------------------
14 Product 1
SELECT [fk_company],[fk_product] FROM CompanyProduct;
fk_company fk_product
----------- -----------
1 14
2 14
3 - The Entity in VS.NET 2008
alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png
The Entity Container Name is 'testEntities' (as seen in model Properties window)
4 - The Code (FINALLY!)
testEntities entity = new testEntities();
var theResultSet = from c in entity.theCompany
select new { company_id = c.id, product_id = c.theProduct.Select(e=>e) };
foreach(var oneCompany in theResultSet)
{
Debug.WriteLine("theCompany.id: " + oneCompany.company_id);
foreach(var allProducts in oneCompany.product_id)
{
Debug.WriteLine("theProduct.id: " + allProducts.id);
}
}
5 - The Final Output
theCompany.id: 1
theProduct.id: 14
theCompany.id: 2
theProduct.id: 14
theCompany.id: 3
IT should be something like this....
var query = from t1 in db.table1
join t2 in db.table2
on t1.Field1 equals t2.field1 into T1andT2
from t2Join in T1andT2.DefaultIfEmpty()
join t3 in db.table3
on t2Join.Field2 equals t3.Field3 into T2andT3
from t3Join in T2andT3.DefaultIfEmpty()
where t1.someField = "Some value"
select
{
t2Join.FieldXXX
t3Join.FieldYYY
};
This is how I did....
You'll want to use the Entity Framework to set up a many-to-many mapping from Company to Product. This will use the CompanyProduct table, but will make it unnecessary to have a CompanyProduct entity set in your entity model. Once you've done that, the query will be very simple, and it will depend on personal preference and how you want to represent the data. For example, if you just want all the companies who have a given product, you could say:
var query = from p in Database.ProductSet
where p.ProductId == 14
from c in p.Companies
select c;
or
var query = Database.CompanySet
.Where(c => c.Products.Any(p => p.ProductId == 14));
Your SQL query returns the product information along with the companies. If that's what you're going for, you might try:
var query = from p in Database.ProductSet
where p.ProductId == 14
select new
{
Product = p,
Companies = p.Companies
};
Please use the "Add Comment" button if you would like to provide more information, rather than creating another answer.
LEFT OUTER JOINs are done by using the GroupJoin in Entity Framework:
http://msdn.microsoft.com/en-us/library/bb896266.aspx
The normal group join represents a left outer join. Try this:
var list = from a in _datasource.table1
join b in _datasource.table2
on a.id equals b.table1.id
into ab
where ab.Count()==0
select new { table1 = a,
table2Count = ab.Count() };
That example gives you all records from table1 which don't have a reference to table2.
If you omit the where sentence, you get all records of table1.
Please try something like this:
from s in db.Employees
join e in db.Employees on s.ReportsTo equals e.EmployeeId
join er in EmployeeRoles on s.EmployeeId equals er.EmployeeId
join r in Roles on er.RoleId equals r.RoleId
where e.EmployeeId == employeeId &&
er.Status == (int)DocumentStatus.Draft
select s;
Cheers!
What about this one (you do have a many-to-many relationship between Company and Product in your Entity Designer, don't you?):
from s in db.Employees
where s.Product == null || s.Product.ProductID == 14
select s;
Entity Framework should be able to figure out the type of join to use.

Resources