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;
Related
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
I am trying to get all records from an entity that do not join to another entity.
This is what I am trying to do in SQL:
SELECT * from table1
LEFT join table2
ON table1.code = table2.code
WHERE table2.code IS NULL
It results in all table1 rows that did not join to table2.
I have it working with Linq when joining on one field, but I have contact records to join on firstname, dob, and number.
I have a "staging" entity that is imported to; a workflow processes the staging records and creates contacts if they are new.
The staging entity is pretty much a copy of the real entity.
var queryable = from staging in linq.mdo_staging_contactSet
join contact in linq.ContactSet
on staging.mdo_code equals contact.mdo_code
into contactGroup
from contact in contactGroup.DefaultIfEmpty()
// all staging records are selected, even if I put a where clause here
select new Contact
{
// import sequence number is set to null if the staging contact joined to the default contact, which has in id of null
ImportSequenceNumber = (contactContactId == null) ? new int?(subImportNo) : null,
/* other fields get populated */
};
return queryable // This is all staging Contacts, the below expressions product only the new Contacts
.AsEnumerable() // Cannot use the below query on IQuerable
.Where(contact => contact.ImportSequenceNumber != null); // ImportSequenceNumber is null for existing Contacts, and not null for new Contacts
Can I do the same thing using method syntax?
Can I do the above and join on multiple fields?
The alternatives I found were worse and involved using newRecords.Except(existingRecords), but with IEnumerables; is there a better way?
You can do the same thing with method calls, but some tend to find it harder to read since there are some LAMBDA expressions in the middle. Here is an example that shows how the two are basically the same.
I've seen others ask this same questions and it boils down to choice by the developer. I personally like the LINQ approach since I also write a bunch of SQL and I can read the code easier.
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
I am trying to write a Linq query that results in a parent entity with one of the fields being a collection of entities of its related children. For example, I have a collection of all customers entities and a collection of all orders entities. The orders entities have a field called customerPK which contains the link to the related parent customer entity. I want to create a Linq query that joins the two collections and results in all the fields of the customer entity plus an additional field which is the collection object of all the related order entities for that specific customer entity.
Hopefully this should do the trick;
EDIT: Code updated to perform a Left Outer Join, based on this example; http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/. This now includes Customers who have no orders.
var query = from c in customers
join o in orders on c.ID equals o.CustomerPK into joined
from j in joined.DefaultIfEmpty()
group j by c into g
select new { Customer = g.Key, Orders = g.Where(x => x != null) };
Note, the use of Where on the selection of the Orders grouping is so that null orders are filtered out at this point, instead of ending up with a grouping containing a single null Order for customers who don't have orders.
Then some example usage;
foreach (var result in query)
{
Console.WriteLine("{0} (ID={1})", result.Customer.Name, result.Customer.ID);
foreach (var order in result.Orders)
{
Console.WriteLine(order.Description);
}
}
This example results in an object with two fields, the Customer and then a group of related Orders, but there's no reason why you can't select the individual fields of your customer object in the query as you specified in your post.
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 }