System.Linq.Dynamic to select a collection inside of a collection from Entity Framework IQueryable - linq

I have an EF model with the relationship User->Roles. It's a one to many relationship in our database. I would like to select the ID from role's record and the name from the user's records.
What I have come up with works for one-to-one relationships. I'm not sure how to generate the a list inside of dynamic linq. Maybe a SelectMany?
User table: Users
Join Table: User_Role
Role Table: Roles
//does not select inside a collection of USER_ROLES
q= query.Select(" new ( ID, (new (USER_ROLES.ID as ID) as USER)")
//not valid
//q = query.Select(" new ( ID, (new List<Object> (USER_ROLES.ID as ID) as USER)") something I figure this would give me a list of User_Role's ID
//not valid
//q = query.Select(" new ( ID, (new List<Object> (USER_ROLES.ROLE.ID as ID) as USER)") something I figure this would give me a list of Role's ID
Update I'm getting closer. I used a selectmany, but the results are duplicated
q = query.SelectMany("USER_ROLES","new (inner as myUSER,outer as myROLE) ").SelectD("new (myROLE.ID as ROLE_ID, new( myROLE.NAME, myUSER.USER.FIRSTNAME,myUSER.USER.ID)as user)")
The results look like this:
Role->User_Role A-> User A
User_Role A-> User B ..notice the repeat of "User_Role A"
User_Role A-> User C
it should be
Role->User Role a -> User A
+ User B
+ User C

Related

Query ManyToMany SpringBoot

I have the following modeling:
table hackathon
idEvent int pk ai
...
table team
idTeam int pk ai
...
table hackathon_has_team
hackathon_id int
team_id int
....
And I need to select all the teams that are in an event by event id and I'm breaking my head with it, can anyone help?
I'm trying to do this but it does not work:
#Query("SELECT t "
+ "FROM Team t INNER JOIN hackathon_has_team "
+ "ON hackathon_has_team.team_id = t.id "
+ "WHERE hackathon_has_team.hackathon_id = :hackathon_id")
public Page<Team> getListAllTeamsByIdOfHackathon(#Param("hackathon_id ") Long id, Pageable pageable);
You might need to provide more to get more, but depending on how you are obtaining the list of the teams, you could try:
select * from event_has_team
where (select team_id from table team)
This selects everything from the event_has_team table where the team_id is in the team table. you can also add a where clause for teams you've identified in that sub-select or nit he main select, depending on what you really need.

Fetch data from two tables in hibernate

I have to fetch students data, whose account status is true from Student and User tables.as account status has been mentioned in User table and remaining information of the student is in student table,i need students registered under particular college since i have to check college_id in where condition.I have tried many ways to join tables but getting error,please help me to get out of this. below is my code
Query query=sessionFactory.getCurrentSession().createQuery("select stud.student_name, stud.college.college_id, stud.enroll_no, stud.enrollment_year from Student stud,User u where stud.college.college_id=:college_id and u.account_active=:account_active");
query.setParameter("college_id", college_Id);
query.setParameter("account_active", true);
List<Student> list_1 = query.list()
u have to join by using pojo like below
Query query=sessionFactory.getCurrentSession().createQuery("
select stud.student_name, stud.college.college_id, stud.enroll_no, stud.enrollment_year
from User u
join u.Student stud
join stud.college college
where college.college_id=:college_id
and u.account_active=:account_active
");
query.setParameter("college_id", college_Id);
query.setParameter("account_active", true);
List<Student> list_1 = query.list()
if Student relationship is availabe in your User table and all pojo must have object of another table in there pojo

LINQ TO Entitites : Combining Two Non Related Tables in Query

I have two tables:
Relationships (ID, UserID, Type, Contact ID)
Contacts (ID, Name, Address)
When the type is 5 in Relationship table, Contact ID is the ID in the Contacts table.
I want to get all the contacts information for a particular user
Here is what I have :
IEnumerable<Relationship> rels = user.Relationships.Where(r => r.Type==5)
foreach (Relationship r in rels)
{
contact = contactRepository.Find(r.ContactID); // Returns Contact Object
Relation relation = new Relation(r, contact);
RelationList.Add(relation);
}
Is this correct way to do this?
I have seen other post mentioning TPC. However, I did not quite understand all that and it seemed TPC only works for code first process.
You can user followng linq statement to get the contacts of a given userID (let's say UserID=15) by using relatonships and contacts tables:
var contacts=from r in Relationships
join c in Contacts on r.ContactID equals c.ID
where r.Type=5 and r.UserID=15
select c;

LINQ where clause

I have the following linq query
var ret = from u in MenuHeaders
.Include("MenuHeaderItems.MenuItem")
select u;
I need to select ONLY menu headers which exist for certain users, which belong to a certain role given a user id.
So, the relational path would be something like this...
MenuHeader RoleMenuHeaders Roles UserRoles Users
---------- --------------- ----- --------- -----
ID <---MenuHeaderID |-> ID <---| UserID----->ID
RoleID -------| |-- RoleID
How do I get my above query to only return MenuHeaders where UserID=1?
If you're using LINQ to Entities, this relationship is probably automatically mapped via properties, and (assuming these are many-to-many relationships, as they appear to be in the schema you show) you can take advantage of the Any operator:
var ret = from mh in MenuHeaders.Include("MenuHeaderItems.MenuItem")
where mh.Roles.Any(r => r.Users.Any(u => u.UserId == 1))
select mh;
Well, you could do it with a join:
var ret = from mh in MenuHeaders.Include("MenuHeaderItems.MenuItem")
join ur in UserRoles on mh.RoleID equals u.RoleID
where ur.UserID == 1
select mh;
(I don't know whether you need Include("UserRoles.UserRole") or anything like that. I don't know which LINQ provider you're using.)
Adding a where clause that references a joined table modifies the resultant query and invalidates the Include.
Check this out.
How to make an Include really include.

How can I use a compound condition in a join in Linq?

Let's say I have a Customer table which has a PrimaryContactId field and a SecondaryContactId field. Both of these are foreign keys that reference the Contact table. For any given customer, either one or two contacts may be stored. In other words, PrimaryContactId can never be NULL, but SecondaryContactId can be NULL.
If I drop my Customer and Contact tables onto the "Linq to SQL Classes" design surface, the class builder will spot the two FK relationships from the Customer table to the Contact table, and so the generated Customer class will have a Contact field and a Contact1 field (which I can rename to PrimaryContact and SecondaryContact to avoid confusion).
Now suppose that I want to get details of all the contacts for a given set of customers.
If there was always exactly one contact then I could write something like:
from customer in customers
join contact in contacts on customer.PrimaryContactId equals contact.id
select ...
...which would be translated into something like:
SELECT ...
FROM Customer
INNER JOIN Contact
ON Customer.FirstSalesPersonId = Contact.id
But, because I want to join on both the contact fields, I want the SQL to look something like:
SELECT ...
FROM Customer
INNER JOIN Contact
ON Customer.FirstSalesPersonId = Contact.id OR Customer.SecondSalesPersonId = Contact.id
How can I write a Linq expression to do that?
It's rarely correct to use join in LINQ to SQL.
Since you want contacts, why not start your selection there? Presuming the association between Customer and Contact is two-way, you should be able to write something like:
IEnumerable<Guid> customerIds = // ...
var q = from contact in Context.Contacts
where customerIds.Contains(contact.Customer.Id)
select contact;
Use anonymous classes. EG
new { A.Foo, B.Bar } equals new { Foo = B.Baz, Bar = C.Ork }

Resources