Linq join between two Entities and 3 Tables [duplicate] - c#

This question already has an answer here:
What is meant by 'The specified LINQ expression contains references to queries that are associated with different contexts'
(1 answer)
Closed 8 years ago.
I am trying to join 3 tables using LINQ from 2 different SQL Servers (entities).
Error: The specified Linq expression contains references to queries that are associated with different contexts
var query = from a in EntityA.TableA
join p in EntityA.TableB
on a.PersonID equals p.PersonID
join m in EntityB.TableC
on Convert.ToInt32(a.SourceID) equals m.ID
where p.someID == "100000527"
select m.ID;
Please help me to resolve this.
Answer:
var query = from a in EntityA.TableA
join p in EntityA.TableB
on a.PersonID equals p.PersonID
where p.someID == "100000527"
select a.ID;
IQueryable<int> ID = null;
foreach (var item in query)
{
int sourceID= Convert.ToInt32(item);
ID = (from m in EntityB.TableC
where m.ID == sourceID
select m.ID).Distinct();
}
return ID;
Is this right approach?

You can only write Linq to SQL Queries on one database at a time.
If you want to join the data together, you will have to write the two queries separately, create anonymous type objects from them, then join them together using plain old Linq on objects.

Related

C# & Entity Framework : return specific columns from a 3 table join

I have a C# application where I am using Entity Framework to pull data from a database. This is the code I am executing:
var person = new List<Person>();
using (DevTestEntities db = new DevTestEntities())
{
person = (from p in db.People
join e in db.PersonEmails on p.Id equals e.Id
join t in db.PersonPhones on p.Id equals t.Id
where t.Phone == phoneNumber
select p).ToList();
}
var str = Newtonsoft.Json.JsonConvert.SerializeObject(person);
return str;
When the code runs, it fails on the select. I assume it is failing because there is a table within the database that is not part of the model. And because there is just a generic select, I assume Entity Framework is selecting all columns from all tables and doesn't know what to do with some of the columns.
What I really want to do is to be able to specify the columns that I want to return to the calling function. How do I specify what columns Entity Framework should select?
Thanks for any assistance.
EF will not fail because of tables in the DB that are not in model. It would help if you provided the error. Also, your query will result in selecting all columns from the People table but not the others.
An example answer to your question is this, it selects three columns from different tables and puts them in a new anonymous type:
var onlySomeColumns = (from p in db.People
join e in db.PersonEmails
on p.Id equals e.Id
join t in db.PersonPhones
on p.Id equals t.Id
where t.Phone == phoneNumber
select new {p.Id, e.email, t.phonenumber}).ToList();

Join a table using on multiple columns using a OR syntax [duplicate]

This question already has answers here:
Linq to Entity Join table with multiple OR conditions
(3 answers)
Closed 6 years ago.
So what I'm trying to do is :-
SELECT * FROM TableA
JOIN TableB ON TableA.OriginPhoneNumber=TableB.Id OR TableA.DestinationPhoneNumber=TableB.Id
Rather strange query I know! But I'm trying to replicate this in EntityFramework/Linq - looking at all the samples I can see a pretty easy way to do it when the join is using an AND (using anonymous types) but does the same result exist for a OR join?
Just do a cross join with a where clause
var results = from a in db.TableA
from b in db.TableB
where a.OriginPhonenumber == b.Id
|| a.DestinationPhoneNumber == b.Id
select new { A = a, B = b };
It's doubtful that an or in a join condition would be more efficient than this, but it's likely that either would result in the same execution plan. Performance aside it will give the same results.
I used Union
var firstJoin=from tbl in TableA
join c in TableB
on c.OriginPhoneNumber Equals tbl.Id
var secondJoin=from tbl in TableA
join c in TableB
on c.DestinationPhoneNumber Equals tbl.Id
var result=firstJoin.Union(secondJoin)

Full outer join with linq for 3 tables [duplicate]

This question already has answers here:
LINQ - Full Outer Join
(16 answers)
Closed 8 years ago.
I have 3 entities in EntityModel: Customer, CustomerAddress (this is junction entity with Ids and orderOnControl columns and cant be ommited in model) and Address. I need to make linq query to FULL JOIN Customer with Address. This query in SQL is plain:
select e1.[AddressID], e1.City, e3.CustomerID, e3.LastName from [SalesLT].[Address] as e1
full join [SalesLT].[CustomerAddress] as e2 on e1.[AddressID] = e2.[AddressID]
full join [SalesLT].[Customer] as e3 on e2.CustomerID = e3.CustomerID
but I need to write this with linq, I found answers where there are 2 entities with many-to-may relation, but couldn't find any with junction entity, I would appreciate any tips
Give this a shot. This LINQ statement will join Customers to Addresses through the junction table CustomerAddress.
var query = from ca in context.CustomerAddress
join a in context.Address on ca.AddressId equals a.AddressId
join c in context.Customer on ca.CustomerId equals c.CustomerId
select new { a.AddressId, a.City, c.CustomerId, c.LastName };

Linq - How to do two select queries? [duplicate]

This question already has answers here:
How to do a subquery in LINQ?
(6 answers)
Closed 9 years ago.
SELECT userid FROM userTable
WHERE userid in (select writeuserid FROM boardTable)
C# LINQ expressions, how to use a query?
I have been using EF4.
userTable, boardTable is connected to the DbContext.
Why not have two different LINQ queries, so that your inner query doesn't execute for each iteration of the outer query.
var query1 = (from t in dbContext.boardTable
select t.writeuserid).ToArray();
var query2 = from r in dbContext.userTable
where query1.Contains(r.userid)
select r.userid;
If your situation is as simple as in the question then you cause join in linq
Assume in here you use Entity FrameWork, so you can use Join to get the result, below is to use the lambda expression:
var result = dbContext.Users.Join(dbContext.Boards,
user => user.UserId,
board => board.WriteUserId,
(u, b) => u.UserId);
why not using join?
var result = (from u in dbcontext.userTable
join u1 in dbcontext.boardTable on u.userid equals u1.writeuserid
select u.userid).FirstOrDefault();
if (result != null)
// do anything else
else
// user not exists

Ruby Sequel Equivalent to LINQ to SQL select anonymous objects

I've got some C# code with a LINQ query I'm trying to translate to Ruby and am using Sequel as my DB ORM. The linq query just performs some joins and then returns an anonymous object containing references to the joined entities. I've got the code translated and operating correctly but it just returns all of the columns from each table and I'd like to wrap each set of columns up in its own object similarly to how it is done in the C# code.
LINQ Query
from s in slots
join tu in _dbContext.table_usages on s.id equals tu.slot_id
join r in _dbContext.Reservations on tu.reservation_id equals r.ReservationID
join o in _dbContext.orders on r.OrderID equals o.OrderID
join c in _dbContext.Contacts on r.ContactID equals c.ContactID
where tu.reservation_id != null &&
r.state != ReservationStates.Cancelled
select new { SlotId = s.id, Reservation = r, Order = o, Contact = c, TableUsage = tu };
Ruby Code:
select(:slots__id, :reservations.*, :orders.*, :restaurant_customers.*, :table_usages.*)
.filter(slots__restaurant_id: restaurant_id, slots__removed: false)
.filter(slots__slot_time: start_time..end_time)
.join(:table_usages, slot_id: :id)
.join(:reservations, id: :table_usages__reservation_id)
.join(:orders, id: :reservations__order_id)
.join(:restaurant_customers, id: :reservations__contact_id)
.filter('table_usages.reservation_id is not null')
.filter('reservations.state != ?', ReservationStates.cancelled)
I'm unable to find a way of accomplishing this via the docs but I thought I would see if anyone has done something similar in a way that I haven't thought of yet.
Thanks!
I'm assuming you are just referring to the last two lines:
.filter('table_usages.reservation_id is not null')
.filter('reservations.state != ?', ReservationStates.cancelled)
Which you could handle via:
.exclude(:table_usages__reservation_id=>nil)
.exclude(:reservations__states=>ReservationStates.cancelled)
exclude operates as an inverse filter.

Categories