LinqtoSql Query In this scenario - c#

Employee Table
Primary Key:EmployeeID
Machine Type Table
Primary Key: MachineTypeID
Machine Table:
Primary Key: MachineID
Foreign Key: MachineTypeID
Foreign Key: EmployeeID
Database structure is described above now I want to query on Machine Table and show following results.
I want to know how to write LinqtoSql query to achieve above table.. is join works here. Kindly help me.

If you have DB/Object Context named context, and also if you don't have navigations on entities(as King King says below your question), you can form a multiple-join query:
var result =
from m in context.Machine
join mt in context.MachineType on m.MachineTypeID equals mt.MachineTypeID
join e in context.Employee on m.EmployeeID equals e.EmployeeId
select new { m.MachineID, mt.Type, e.EmployeeName, m.Price, m.Male, m.Year };

var result = Machine
.Join
(
MachineType,
x=>x.MachineTypeID,
x.MachineTypeID,
(m,mt)=>new
{
m.MachineID,
m.EmployeeID,
m.Price,
m.Make,
m.Year,
mt.Type
}
)
.Join
(
Employee,
x=>x.EmployeeID,
x=>x.EmployeeID,
(m,e)=>new
{
m.MachineID,
MachineType = m.Type,
Employee = m.EmployeeName,
m.Price,
m.Make,
m.Year
}
);

Something like the below will get you started:
This uses navigation properties instead of joins.
var result = context.Machines.Where(x => x.EmployeeID == 3)
.Select(v => new
{
v.MachineID, // from Machines table
v.MachineTypes.MachineType, // from MachineTypes table
v.Employees.EmployeeName, // from Employees table
v.Price, // from Machines table
v.Make, // from Machines table
v.Year // from Machines table
});

Related

C# linq expression not pulling the data correctly

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();

How to get two table value using Linq

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...
};

Linq select Item where it is equal to ID in another table

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

How to update linq query result

I will explain my issue using example.
lets say I have linq query result.
var result1=from c in client
select new my_type
{
...
stockDesctiption=??
};
We will say Client has filed called stockId. this is the same as stockId in the dammadgeStockHistory table. these table are not connected in any foreign key constrain.
if i need to get the dammadgeStockHistory.stockDescrption for each client how to do this.
Join tables by this field (foreign key constraint is not required for that):
var result1 = from c in client
join dsh in dammadgeStockHistory
on c.stockId equal dsh.stockId
select new my_type
{
stockId = c.stockId,
// ...
stockDesctiption = dsh.stockDescrption
};
UPDATE If you want to do 'left join':
var result1 = from c in client
join dsh in dammadgeStockHistory
on c.stockId equal dsh.stockId into g
from cdsh in g.DefaultIfEmpty()
select new my_type
{
stockId = c.stockId,
// ...
stockDesctiption = cdsh == null ? null : dsh.stockDescrption
};

Linq to Entities (EF): How to get the value of a FK without doing the join

I'm using the Linq to Entities. I've got my main table, Employee setup with a field named vendorID. Vendor ID is a foreign key into the Vendors table.
As it is right now, the Employee object does not directly expose the vendorID. Instead, I can only access it this way:
var employee = (from e in context.Employees.Include("tbl_vendors")
where e.employeeID = 1
select e).FirstOrDefault();
//this gets the vendor ID
int vendorID = employee.tbl_vendors.vendorID;
That is just fine and dandy, but it is extra work on the database because it is forcing a join where none is needed. Is there a way to get that key value without being forced to do a join to the tbl_vendors table?
Actually this is very simple you basically do this:
var tblVendorID = (from e in context.Employees
select e.tbl_vendors.ID).FirstOrDefault();
Even though this looks like you are doing a join L2E will optimize out the join.
Which you can confirm with code like this:
var results = from e in ctx.Employees
select e.tbl_vendors.ID;
var query = results as ObjectQuery<int>;
string sql = query.ToTraceString();
Hope this helps
Alex (Microsoft).
You can access the foreign key via the entity reference.
Employee employee = context.Employees.Single(e => e.employeeID == 1);
Int32 vendorID = (Int32)employee.tbl_vendorsReference.EntityKey.
EntityKeyValues[0].Value;
See MSDN for reference on the EntityReference and EntityKey classes.
Not sure about your object names here but you can grab the key from the entity key property without going to the database something like this:
var employee = (from e in context.Employees
where e.employeeID = 1
select e).FirstOrDefault();
//this gets the vendor ID
int vendorID = (int)employee.tbl_vendorsReference.EntityKey.EntityKeyValues[0].Value;

Categories