Querying a join table using LINQ - c#

Okay this could very likely be a silly question. I am using Entity Framework Code First. I have two classes, User and Event, that have a Many-To-Many relationship. When EF generates my database tables, it creates a join table, which I call Users_Events. This table has two columns, User_ID and Event_ID. Everything is fine so far.
I want to pull an Event from my database and serialize it to JSON. This also works perfectly except I cannot pull an Event's Users because this would create a circular reference. What I want to do here is query my join table and get all the User_IDs that have an associated Event_ID equal to the ID of the Event I am serializing.
How can I do this?

I don't know exactly what you want to end up with in your JSON, but I suspect you want to select into a new anonymous type and serialize that instead. Something along these lines maybe:
from e in myContext.Events
where e.ID = 123
select new {
Event = e,
UserIDs = (from u in e.Users select u.ID)
}

Related

How to select data from entity framework without selecting its icollection(foreign table)

I am using C# to select data from my database. Now i have two table, the first one is aspnetuser, the second one is aspnetuserroles, the aspnetuserroles have the foreign key linkage with aspnetuser table, when i perform the following query
db.AspNetUsers.ToList()
the aspnetroles data will appeared in the aspnetusers data. This will cause my datatable unable to display its data because datatable expect one value in one column parameter. If the aspnet roles data inside that json, it will appear as multiple row and datatable dont accept it.. If i remove that foreign key linkage, my datatable will display without any error.
In this case, what i want is, how to select aspnetusers table without pulling out its foreign table. For eg
db.AspNetUsers.Select(x=>x.AspNetUsers).ToList();
Turn off the LazyLoading. So that the children will not be fetched automatically.
try doing something like this (good for keeping the return object light and leave behind any unwanted columns):
(I have just made up some col name, but you get the idea.)
var result = (from a in db.AspNetUsers
select new AspNetUser { Name = a.Name,
othercol1 = a.othercol1,
othercol2 = a.othercol2,
}).ToList();
Footnote: In reality it is generally not good practice to return the actual db Entity to the front end so you might want to have your own Data Transfer Objects (DTO).
You configured that in the mappings using the Fluent API's methods
HasOptional
HasMany
Ignore
etc. But normally, I create schema-bound views in database and then map that in EF. It works really well in cases when we're only interested in a flattened query without all the joints.
Or use Linq to EF projections as JonhB's answer...
var result = (from a in db.AspNetUsers
select new AspNetUser { Name = a.Name,
...
}).ToList();
Just make sure you don't call ToList on db.AspNetUsers because that would materialize the query on AspNetUsers and all it's foreign key references and as result the projection is done in-memory after the query returns

Linq code for joining many to many tables

I'm new at linq and need for your advice.
I created three tables.
STUDENT ---- STUDENT_COURSE ----- COURSES
I simply want to list which students are taking which courses.
If I'm using dbml to doing this, I get the result in somehow like below.
var takencourses = from sc in dbe.STUDENT_COURSEs
join s in dbe.Students on sc.SID equals s.ID
join c in dbe.COURSEs on sc.CID equals c.Id
select new { s.NAME, s.SURNAME, c.COURSENAME};
dataGridView1.DataSource = takencourses;
But I'm not able to run this with Entity Data Model.
When I'm adding entity data model STUDENT_COURSE table is disappearing and its adding references on the tables like below.
Because I didn't have the STUDENT_COURSE table I couldn't write the LINQ for joining Student and Courses tables to get the result.
I simply want to take NAME, SURNAME, COURSENAME from Entity Data Model.
So how can I do it with using Entity Data Model?
What should be the equivalent lambda code for this?
For Example I tried something like this dbe.Students.SelectMany(s => s.STUDENT_COURSEs).ToList() but I didn't find the correct result.
If I'm going to working on 100.000 rows, what will be the best choice for performance issues?
Thanks for your answers.

LINQ to SQL - Using 'Select new' and navigation / child tables

I've constructed a LINQ to SQL statement that pulls back records via an Entity Framework. The child tables are populated automatically (I think this is called navigation?) Now I have a CLOB field present which means I have to construct the statement to send to a list first, then make distinct:
var getResult = (from u in _dbRo.ParentTable
join t in _dbRo.ChildTAble on u.ID equals t.PARENT_ID
where
u.CURRENT == "Y"
select u).ToList().Distinct().ToList();
The problem I have with this, although it works is it's very inefficient. Because a DISTINCT is not wrapped around the generated SQL (I've got a monitoring tool which confirms this) I end up with around 80 records, but in reality there is only 7 when the duplications on the fields I'm after are taken out.
I've tried using the below 'select new':
select (MainTable) new MainTableInheritance
{
Examplefield = u.Examplefield,
ChildTableRecords= u.ChildTableRecords
}
And it's here that I start having problems. I just can't get the child tables to populate. ChildTableRecords is an entity set, and despite trying a few methods I've not had any luck.
Does anyone have any suggestions?

working with multiple tables

I have a c# project where I am using a MS access database, and I am trying to put some items from two (related) tables, in the same listView.
This is the code that I have:
Where it sais "none" is the place where I want to put an item from the other table, but i don't know how. Since they have a relationship I thought that was possible to call items from one table or another.
Please note that I am fairly new to c# and working with databases.
You should join the two tables together to get the unified result.
You could do something like this:
select c.*
, s.otherFieldYouNeed
from ClientsT c
join SomeOtherTable s
on c.someId = s.someId
since the two table are related you can use a join query to get the desired result:
select FirstName,LastName,'none',CellPhone,ClientID from Clients inner join mySecondTable
on Clients.mysharedField=mySecondTable.mysharedField
select FirstName,LastName,(select none from SecondTable where Clients.Field= SecondTable.Field),CellPhone,ClientID from Clients
Try altering your query to include this information. Something like:
Select FirstName, LastName, ColumnFromOtherTable, CellPhone, ClientsT.ClientID
from ClientsT, OtherTable where ClientsT.ClientID=OtherTable.ClientID
Of course, in order to do this, you have to have a corresponding ID field in both tables.

Is it possible to specify a database and schema within a linqtosql query?

I am using linqtosql to query a database directly (not as am ORM).
I have the following code which works:
var events =
from e in Events
select e.EventID;
What I would like to do is expand it to join to a second table within a different database / schema on the same SQL instance. For example:
var events =
from e in Events
join p in database2.dbo.People on p.PersonID equals e.PersonID
select e.EventID;
How would I go about specifying the database / schema within the linq query?
I do not think it is possible out of the box. But if you only want a select, you can create a view to the second database and add that to your DBML.

Categories

Resources