Join on tables from different DbContext - model first - entity-framework

In an app with EF6.0, I have two DbContext's created by model first, Schema1.DbContext1 and Schema2.DbContext2.
Now I need to do a join on two entities, EntityA from Schema1.DbContext1 and EntityB from Schema2.DbContext2.
How can I do this?

Have you tried just doing it?
Something like:
var result = context1.EntityA.Join(context2.EntityB, a=>a.Key, b=>b.Key, (a,b)=>new {a,b});
I'm not sure how nice the SQL will be, since the join is done in LINQ. You'd want to test and see how it is actually being implemented!

If you can use stored procedures, this is a case for it. The proc can join the two entities at the database level across databases. Whichever db is appropriate, you can then map that proc in your entities model and use it. I say 'if you can' because I've seen shops that prohibit all SP's in favor of only EF.

Related

JPA ManyToMany filter on link table

We have a many to many relation with let's say Entity1 and Entity2.
Now when we delete an element of Entity2, we don't in fact remove it from database but simply have a field "isActive" which we set to false.
When that happens, we would like however to remove all relations between any element of Entity1 to the element of Entity2 which was "deleted".
In SQL this transforms to a entity1 table, entity2 table, and entity1TOentity2 table. In SQL we can simply do a single update,
delete from entity1TOentity2 where entity2ID = :entity2Id
In JPA, we could load all elements of Entity1 as objects, with a join fetch on the relation, then remove one by one in Java the connections, but it's terribly wasteful...
Is there any way to formulate that SQL query with JPAQL?
I know it's possible to explicitly define a link entity, and make JPA use it, then I guess I could run a query basically identical to the SQL one on that link entity, but it seems a bit overkill.
am I missing a solution as nice as the raw SQL, but using the JPA API/JPAQL?
Given your context, I see only one option: native queries.
On pure JPA, I don't know a clean way to do it.
If you're using Hibernate behind the scenes, there is a high-level solution:
#Entity
#Where(clause='isActive=true')
public class Entity2{
}

Whats the best way to join two tables with no database relationship using EF?

Ok, lets say you have two tables: Order and OrderLine and for some reason they do not have a foreign key relationship in the database (it's an example, live with it). Now, you want to join these two tables using Entity Framework and you cook up something like this:
using (var model = new Model())
{
var orders = from order in model.Order
join orderline in model.OrderLine on order.Id equals orderline.OrderId into orderlines
from ol in orderlines.DefaultIfEmpty()
select new {order = order, orderlines = orderlines};
}
Now, the above will produce orders and orderlines, left-joined and all, but it has numerous issues:
It's plain ugly
It returns an anonymous type
It returns multiple instances of the same order and I you have to do Distinct() on the client side because orders.Distinct() fails.
What I am looking for is a solution which is:
Pretty
Returns a statically well-known type instead of the anonymous type (I tried to project the query result, but I got into problems with the OrderLines)
Runs Distinct on the server side
Anyone?
Even if the database tables do not have a foreign key relationship setup, you can configure Entity Framework as if they do.
Add an OrderDetails navigation property to your Order class and then just query Orders.

can I perform a query inside of JPA entity to get back a single column

I have a dumb question. It would be great if this could be done, but I am not holding my breath.
I need a single column from a table linked to my JPA entity to be a collection in said JPA entity. Is there any way, that I can just get back that column alone that is related to that entity, instead of having to get back an entire table (which could be very costly?)
Can I perform a query inside that JPA entity that will be performed and loaded eagerly into a collection?
I am trying to avoid having to make several calls to the database by just executing a couple of queries.
What are your thoughts on this?
#ElementCollection(fetch=FetchType.EAGER)
#CollectionTable(name="QUICK_LAUNCH_DISTLIST",joinColumns=#JoinColumn(name="QUICK_LAUNCH_ID"))
#Column(name="LIST_ID")
private List<Long> distListIDs;
The ElementCollection attribute is what I was looking for. It seems to work pretty well in addition to that.
Thanks for the help and inspiration guys.
Suppose a Category has many products:
select product.name from Category c inner join c.products product where ...
If that's not what you want, please show an example in your question.

entity framework: join on the rule "A = substring(B)"?

Could I ask somebody show me the way how to declare the association between two entities 'Record' and 'DictionaryItem' if corresponded tables on the DB level are joined by such interesting rule:
FROM Records R LEFT OUTER JOIN DictionaryItems D
ON SUBSTRING(R.CompositeKey,3,8) = D.DictionaryItemId
P.S. I'm now working with POCO entities.
Linq-to-entities doesn't support Substring. You must either execute SQL directly by calling context.Database.SqlQuery<> or you must use Entity SQL - that would probably require converting DbContext to ObjectContext via IObjectContextAdapter, creating ObjectSet and running ESQL query.

How to sort related entities with eager loading in ADO.NET Entity Framework

Greetings,
Considering the Northwind sample tables Customers, Orders, and OrderDetails I would like to eager load the related entities corresponding to the tables mentioned above and yet I need ot order the child entities on the database before fetching entities.
Basic case:
var someQueryable = from customer in northwindContext.Customers.Include("Orders.OrderDetails")
select customer;
but I also need to sort Orders and OrderDetails on the database side (before fetching those entities into memory) with respect to some random column on those tables. Is it possible without some projection, like it is in T-SQL? It doesn't matter whether the solution uses e-SQL or LINQ to Entities. I searched the web but I wasn't satisfied with the answers I found since they mainly involve projecting data to some anonymous type and then re-query that anonymous type to get the child entities in the order you like. Also using CreateSourceQuery() doesn't seem to be an option for me since I need to get the data as it is on the database side, with eager loading but just by ordering child entities. That is I want to do the "ORDER BY" before executing any query and then fetch the entities in the order I'd like. Thanks in advance for any guidance. As a personal note, please excuse the direct language since I am kinda pissed at Microsoft for releasing the EF in such an immature shape even compared to Linq to SQL (which they seem to be getting away slowly). I hope this EF thingie will get much better and without significant bugs in the release version of .NET FX 4.0.
Actually I have Tip that addresses exactly this issue.
Sorting of related entities is not 'supported', but using the projection approach Craig shows AND relying on something called 'Relationship Fixup' you can get something very similar working:
If you do this:
var projection = from c in ctx.Customers
select new {
Customer = c,
Orders = c.Orders.OrderByDescending(
o => o.OrderDate
)
};
foreach(var anon in projection )
{
anon.Orders //is sorted (because of the projection)
anon.Customer.Orders // is sorted too! because of relationship fixup
}
Which means if you do this:
var customers = projection.AsEnumerable().Select(x => x.Customer);
you will have customers that have sorted orders!
See the tip for more info.
Hope this helps
Alex
You are confusing two different problems. The first is how to materialize entities in the database, the second is how to retrieve an ordered list. The EntityCollection type is not an ordered list. In your example, customer.Orders is an EntityCollection.
On the other hand, if you want to get a list in a particular order, you can certainly do that; it just can't be in a property of type EntityCollection. For example:
from c in northwindContext.Customers
orderby c.SomeField
select new {
Name = c.Name,
Orders = from o in c.Orders
orderby c.SomeField
select new {
SomeField = c.SomeField
}
}
Note that there is no call to Include. Because I am projecting, it is unnecessary.
The Entity Framework may not work in the way you expect, coming from a LINQ to SQL background, but it does work. Be careful about condemning it before you understand it; deciding that it doesn't work will prevent you from learning how it does work.
Thank you both. I understand that I can use projection to achieve what I wanted but I thought there might be an easy way to do it since in T-SQL world it's perfectly possible with a few nested queries (or joins) and order bys. On the other hand seperation of concerns sounds reasonable and we are in the entity domain now so I will use the way you two both recommended though I have to admit this is easier and cleaner to achieve in LINQ to SQL by using AssociateWith.
Kind regards.