I am trying to query two tables and need to pull related records from both the tables. I am using enityframeworkcore 3 One is system versioned table and the other is history table. My resultset is containing data only from history table and not system-versioned table. Could somebody tell me what is wrong with my statement . I am ensured that the personid in the systemversion table matches the history table.
Query
var personNotes = (from pn in _context.PersonNotes
join pnh in _context.PersonNotesHistory on pn.PersonId equals pnh.PersonId
select pn);
return personNotes;
You need to specify the column names you want to return in the result:
var personNotes = (from pn in _context.PersonNotes
join pnh in _context.PersonNotesHistory on pn.PersonId equals pnh.PersonId
select new {
data1 = pn.column1,
data2 = pn.column2,
data3 = pn.column3,
data4 = pnh.column1,
data5 = pnh.column2,
data6 = pnh.column3,
}).ToList();
return personNotes;
Just change the column1, column2, column3 with column names you want to retrieve from the database.
As an alternative to the first answer you may use this syntax:
var personNotes = _context.PersonNotes
.Join(_context.PersonNotesHistory, pn => pn.PersonId, pnh => pnh.PersonId, (pn, pnh) => new
{
pn.Note,
pn.AuthorID,
pn.CreatedBy,
pnh.Note,
pnh.AuthorID,
pnh.CreatedBy
})
.ToList();
Related
I have tow tables - OrderRequisition and Order. I can show all the records from OrderRequisition table using linq query:
var list = (from r in db.OrderRequisition
select new SalesOrderViewModel
{
OrderId = r.OrderId ,
OrderNo = r.OrderNo
}).ToList();
I want to show only those records from OrderRequisition table which are not included in Order table. Any clue
Thanks
Partha
A simple approach that might be efficient enough because your database is able to optimize it:
var list = db.OrderRequisition
.Where(or => !db.Order.Any(o => o.OrderId == or.OrderId))
.ToList();
(skipped the SalesOrderViewModel initialization because not relevant for the question)
I have two table one is Administrator table and another is Teacher table .
I want to display these both tables values in single Gridview .
I have make id as a primary key in Administrator table and make this tech_id as foreign key in Teacher table .
Now how to get these table values together in single gridview as shown in pic
Now please any body help me how to get these two value together using Linq .
I have try but I can't make any more
private void loadgri()
{
StudentDatabaseEntities empl = new StudentDatabaseEntities();
var query=from g in empl.Teachers
join m in empl.Administrators on g.id equals m.id
where m.username=="cs"
select new{
Name = g.username,
};
}
You don't need a join if you have already a navigation-property:
var query= from t in empl.Teachers
where t.Administrator.username == "cs"
select new { Teacher = t.username, Administrator = t.Administrator.username };
This is just an example, but you see that you can access all properties of both entities.
Don’t use Linq’s Join. Navigate!
To show all the teachers and their administrator, you don't have to use "join", you could just use the navigation property:
var query = from g in empl.Teachers
where g.Administrator.username=="cs"
select new {
Teacher_Id = g.Id,
Teacher_Name = g.username,
Administrator_Id = g.Id,
Administrator_Name = g.Administrator.username,
//etc...
};
I am not sure how possible this is but I have two tables and I want to grab a value from table 2 via the value of table 1.
Table 1 has the a Foreign Key called "rank" which is an int. Table 2 has a value called "name" which is a string. Now Table 1's "rank" correlates to Table 2's "ID".
So when I say
var result =
db.Table1.Select(x => new { x.name, x.rank }).ToList();
//Bob - 2
I really want to say something like
var result =
db.Table1.Select(x => new { x.name, Table2.rank.Where(ID == x.rank) }).ToList();
//Bob - Gold
I am still new to LINQ though and I am not sure how to get rank's string value from the other table within a query like this.
EDIT
Tables I am using and their relational values.
User: ID (PK), s1elo (FK to PastElos), champ (FK to ChampionList), elo (FK to EloList)
PastElo: ID (PK), Rank
ChampionList: ID (PK), name
EloList: ID (PK), Rank
Working example for Users and PastElo
var result =
db.Users.Join(db.PastEloes,
x => x.s1elo, y => y.ID, (x, y)
=> new { y.Rank, x.name, x.other_items_in_Users }).ToList();
Note: PastElo is PastEloe's due to EF making everything plural when I synced up my DB, thus why User is also Users, I think that is referred to as the "context".
You could try something like the following:
var result = db.Table1.Join(db.Table2,
x=>x.rank,
y=>y.ID,
(x,y) => new { x.rank, y.Name }).ToList();
In the above linq query we make a Join between the two tables, Table1 and Table2 based on the association and then we select that we want.
Another way you could try to write this query would be the following:
var result = (from t1 in db.Table1
join t2 in db.Table2
on t1.rank equals t2.ID
select new { t1.rank, t2.Name, }).ToList();
Another way to do this would be to include your Database relationships in your C# entities. You could use EntityRef here. See the following documentation:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/how-to-map-database-relationships
Let's say I have a table that holds shipping history. I'd like to write a query that counts the amount of shipments per user and gets the shipping name from the most recent entry in the table for that user.
Table structure for simplicity:
ShipmentID
MemberID
ShippingName
ShippingDate
How do I write a LINQ C# query to do this?
It sounds like might want something like:
var query = from shipment in context.ShippingHistory
group shipment by shipment.MemberID into g
select new { Count = g.Count(),
MemberID = g.Key,
MostRecentName = g.OrderByDescending(x => x.ShipmentDate)
.First()
.ShipmentName };
Not really a LINQ answer, but personally, I'd be dropping to SQL for that, to make sure it isn't doing any N+1 etc; for example:
select s1.MemberID, COUNT(1) as [Count],
(select top 1 ShippingName from Shipping s2 where s2.MemberID = s1.MemberID
order by s2.ShippingDate desc) as [LastShippingName]
from Shipping s1
group by s1.MemberID
You can probably do LINQ something like (untested):
var qry = from row in data
group row by row.MemberId into grp
select new {
MemberId = grp.Key,
Count = grp.Count(),
LastShippingName =
grp.OrderByDescending(x => x.ShippingDate).First().ShippingName
};
I am using a linq query to obtain a table of customers with their total money amount for each monetary unit exist in my database(this one is ok.)
when show the result of my query with Microsoft Report Viewer the result is like Table 1 but what i want is Table 2, only the customer name like "A" and a cell with all the monetory unit records > 0.
Is there any way you can suggest?
This is my code which produces Table 1:
var query = from kur in kurToplamlist
join cariBilg in db.TBLP1CARIs
on kur.CariIdGetSet equals cariBilg.ID
select new
{
cariBilg.ID,//customerid
EUROBAKIYE = cariBilg.HESAPADI,
cariBilg.K_FIRMAADI,//other column names
cariBilg.K_YETKILIADI,//other column names
cariBilg.K_FIRMATELEFON,//other column names
cariBilg.K_YETKILITELEFON,//other column names
AUDBAKIYE = cariBilg.B_CEPTELEFON,//other column names
MonetaryUnit = String.Concat(kur.KurToplamMiktarGetSet.ToString(), kur.DovizTuruGetSet.ToString()),//concatenates "100" and "TL/USD etc."
};
What i want is to obtain Table 2 in the image
Thank you in advance.
Table image
var query = from kur in kurToplamlist
where kur.KurToplamMiktarGetSet > 0
join cariBilg in db.TBLP1CARIs
on kur.CariIdGetSet equals cariBilg.ID
select new
{
cariBilg.ID,
EUROBAKIYE = cariBilg.HESAPADI,
cariBilg.K_FIRMAADI,
cariBilg.K_YETKILIADI,
cariBilg.K_FIRMATELEFON,
cariBilg.K_YETKILITELEFON,
AUDBAKIYE = cariBilg.B_CEPTELEFON,
TLBAKIYE = String.Concat(kur.KurToplamMiktarGetSet.ToString(), kur.DovizTuruGetSet.ToString()),
};
var dfg = from qre in query
select qre.TLBAKIYE;
var aq = (from qw in query
select new {
qw.ID,
EUROBAKIYE = qw.EUROBAKIYE,
qw.K_FIRMAADI,
qw.K_YETKILIADI,
qw.K_FIRMATELEFON,
qw.K_YETKILITELEFON,
AUDBAKIYE = qw.AUDBAKIYE,
TLBAKIYE = String.Join(",", (from qre in query
where qre.ID == qw.ID
select qre.TLBAKIYE).Distinct())
}).Distinct();
return aq;
This is my answer.