EF reference lookup - entity-framework

I load list of invoices, and I also loaded list of customers, using the same context. If I want to display invoices in a grid, where one column will contain customer's name, I need to somehow fix-up the relationship between the invoices and the customers.
How can I do this?

The problem was that customers list was retrieved with MergeOption.NoTracking, so it was detached from context, and it could not look for relationship.

Related

JPA fetching too many entries

I have a Customer Entity with a OneToMany relationship to an Invoice Entity.
In plain old sql i can do "select customer_name,customer_age,[some other fields] from customer, invoice where ... [put some filtering here]", which gets me exactly one record with the fields i need.
In JPA i use "select c from Customer c join c.invoiceCollection where ... [same filtering as above]"
This works, but i get the Customer entity with all its associated invoices.
This is nonsense, because i pull a huge amount of (invoices) data from the database, which i do not need. I need only my customer data with exactly one invoice, as specified in the where clause.
To make things worse, i have to loop over the Customer.invoiceCollection in order to find the one specific invoice needed. This costs me even more time plus it exposes my "where" clause to the middle-tier.
Question: is there a JPA select syntax which fetches exactly one record from a one-to-many relationship, as defined in the where clause?
Things tried so far:
a) lazy loading. This does not work, throws an exception whenever i try to access Customer.invoiceCollection.
Even if it worked, i'd get a Collection with some 1000 entries, which i do not need.
b) changed my jpa statement to "select c,i from Customer c join c.invoiceCollection i where ...". This returns me an array of objects, which i have to manually map to a Customer / Invoice entity.
It works, but it makes the ORM philosophy obsolete. If i perform all the mapping from relational database records/fields to java objects manually in my code, why do i need JPA?
This is one of the most infuriating things about JPA. For example, you NEED the OneToMany side if you want Customer to cascade delete Invoices. In most cases you'd like to tell Invoices to delete itself when a Customer is deleted so that Customer does not necessarily need to know about Invoice.
My suggestion for you is that you keep the OneToMany there but get the Lazy Loading working. In your code, do not access "Customer#getInvoices" directly (unless you really need all of them).
This will allow you to do queries on customers that join to invoices without loading them.
I'm guess the exception you are getting just has to do with transaction boundaries which can be easily fixed.
For a lot of these relationships I often add the OneToMany as a private instance variable but I don't create the #getter method. That way I can use it in queries, setup cascade delete, etc. but I don't provide a way to accidentally load thousands of invoices from a customer.
Oh, and for those queries where you need exactly one invoice with its associated customer you should just do the JPA query on the Invoice and then call #getCustomer on that invoice object. That will be eagerly fetched for you.
If you need exactly one invoice with the related customer, why don't you create a query simply based on Invoice?
select i from Invoice i where [same filtering..]
You should not use one-to-many relationship in this case.
One-to-many relationships are suitable for situations when objects at "many" side are logical parts of object at "one" side (e.g. relationship from Invoice to InvoiceLine).
In you case you need a unidirectional many-to-one relationship from Invoice to Customer, so that you can query it as follows:
select i from Invoice i where ...
Then you can use customer field of Invoice to access Customer or filter by its properties.

Handling Many to Many - Entity Framework

I have an MVC app I am building as a learning project. I have a table with Payees, and a table with Categories. Certain Payees can make transactions of certain categories. For example, Payee A can make payments to Categories A, B and C. Payee B can maybe payments to categories B, C and D.
So, I have a PayeeCategory linking table, with a PayeeId and a CategoryId.
So see the categories the payee can make transactions against, it's a simple Select from PayeeCategory where PayeeId = this.PayeeId. And I join to the Category table to get the category names.
In the view, when I edit a Payee, I need to display a list of all categories, and and allow the user to select or unselect the categories that the current Payee is associated to.
So, in my ViewModel, I'd have a list of categorySelectableItems, which has maybe the CategoryId, the DisplayName and a Selected boolean field. To get the data, I need to Select from Categories, LEFT JOIN PayeeCategory, and where PayeeCategoryId is null, set the Selected to false, else true.
How would I do that ina single Linq statement?
Then, when the data comes back... how would I save the data? Would I have to delete all the relationships, and then re-add them based on the List<> values I get back?
Hope someone can guide me.
This was answered in a different question.
Linq query assistance

Entity Framework many-to-many question

Please help an EF n00b design his database.
I have several companies that produce several products, so there's a many-to-many relationship between companies and products. I have an intermediate table, Company_Product, that relates them.
Each company/product combination has a unique SKU. For example Acme widgets have SKU 123, but Omega widgets have SKU 456. I added the SKU as a field in the Company_Product intermediate table.
EF generated a model with a 1:* relationship between the company and Company_Product tables, and a 1:* relationship between the product and Company_Product tables. I really want a : relationship between company and product. But, most importantly, there's no way to access the SKU directly from the model.
Do I need to put the SKU in its own table and write a join, or is there a better way?
I just tested this in a new VS2010 project (EFv4) to be sure, and here's what I found:
When your associative table in the middle (Company_Product) has ONLY the 2 foreign keys to the other tables (CompanyID and ProductID), then adding all 3 tables to the designer ends up modeling the many to many relationship. It doesn't even generate a class for the Company_Product table. Each Company has a Products collection, and each Product has a Companies collection.
However, if your associative table (Company_Product) has other fields (such as SKU, it's own Primary Key, or other descriptive fields like dates, descriptions, etc), then the EF modeler will create a separate class, and it does what you've already seen.
Having the class in the middle with 1:* relationships out to Company and Product is not a bad thing, and you can still get the data you want with some easy queries.
// Get all products for Company with ID = 1
var q =
from compProd in context.Company_Product
where compProd.CompanyID == 1
select compProd.Product;
True, it's not as easy to just navigate the relationships of the model, when you already have your entity objects loaded, for instance, but that's what a data layer is for. Encapsulate the queries that get the data you want. If you really want to get rid of that middle Company_Product class, and have the many-to-many directly represented in the class model, then you'll have to strip down the Company_Product table to contain only the 2 foreign keys, and get rid of the SKU.
Actually, I shouldn't say you HAVE to do that...you might be able to do some edits in the designer and set it up this way anyway. I'll give it a try and report back.
UPDATE
Keeping the SKU in the Company_Product table (meaning my EF model had 3 classes, not 2; it created the Company_Payload class, with a 1:* to the other 2 tables), I tried to add an association directly between Company and Product. The steps I followed were:
Right click on the Company class in the designer
Add > Association
Set "End" on the left to be Company (it should be already)
Set "End" on the right to Product
Change both multiplicities to "* (Many)"
The navigation properties should be named "Products" and "Companies"
Hit OK.
Right Click on the association in the model > click "Table Mapping"
Under "Add a table or view" select "Company_Product"
Map Company -> ID (on left) to CompanyID (on right)
Map Product -> ID (on left) to ProductID (on right)
But, it doesn't work. It gives this error:
Error 3025: Problem in mapping fragments starting at line 175:Must specify mapping for all key properties (Company_Product.SKU) of table Company_Product.
So that particular association is invalid, because it uses Company_Product as the table, but doesn't map the SKU field to anything.
Also, while I was researching this, I came across this "Best Practice" tidbit from the book Entity Framework 4.0 Recipies (note that for an association table with extra fields, besides to 2 FKs, they refer to the extra fields as the "payload". In your case, SKU is the payload in Company_Product).
Best Practice
Unfortunately, a project
that starts out with several,
payload-free, many-to-many
relationships often ends up with
several, payload-rich, many-to-many
relationships. Refactoring a model,
especially late in the development
cycle, to accommodate payloads in the
many-to-many relationships can be
tedious. Not only are additional
entities introduced, but the queries
and navigation patterns through the
relationships change as well. Some
developers argue that every
many-to-many relationship should start
off with some payload, typically a
synthetic key, so the inevitable
addition of more payload has
significantly less impact on the
project.
So here's the best practice.
If you have a payload-free,
many-to-many relationship and you
think there is some chance that it may
change over time to include a payload,
start with an extra identity column in
the link table. When you import the
tables into your model, you will get
two one-to-many relationships, which
means the code you write and the model
you have will be ready for any number
of additional payload columns that
come along as the project matures. The
cost of an additional integer identity
column is usually a pretty small price
to pay to keep the model more
flexible.
(From Chapter 2. Entity Data Modeling Fundamentals, 2.4. Modeling a Many-to-Many Relationship with a Payload)
Sounds like good advice. Especially since you already have a payload (SKU).
I would just like to add the following to Samuel's answer:
If you want to directly query from one side of a many-to-many relationship (with payload) to the other, you can use the following code (using the same example):
Company c = context.Companies.First();
IQueryable<Product> products = c.Company_Products.Select(cp => cp.Product);
The products variable would then be all Product records associated with the Company c record. If you would like to include the SKU for each of the products, you could use an anonymous class like so:
var productsWithSKU = c.Company_Products.Select(cp => new {
ProductID = cp.Product.ID,
Name = cp.Product.Name,
Price = cp.Product.Price,
SKU = cp.SKU
});
foreach (var
You can encapsulate the first query in a read-only property for simplicity like so:
public partial class Company
{
public property IQueryable<Product> Products
{
get { return Company_Products.Select(cp => cp.Product); }
}
}
You can't do that with the query that includes the SKU because you can't return anonymous types. You would have to have a definite class, which would typically be done by either adding a non-mapped property to the Product class or creating another class that inherits from Product that would add an SKU property. If you use an inherited class though, you will not be able to make changes to it and have it managed by EF - it would only be useful for display purposes.
Cheers. :)

Core Data - Associate a Quantity to a Relationship

I have a Core Data entity called "Item" and it represents an item in a store so it has a name, price, and a few other attributes.
I would like to be able to create lists of these items and I am having some trouble figuring out how to do it.
The problem is that I need to be able to associate a quantity for each item in the list AND I need to be able to add the item to multiple lists.
So for example, say I have an item called "Bread" and I want to add it to two different lists with different quantities associated with each relationship.
I see that the documentation for Core Data says that a userInfo dictionary can be associated with a relationship but I can't seem to locate any information that would indicate whether or not that would work for me.
Any ideas?
This is probably not the best place for a userInfo dictionary. Instead, create a new entity, which has a list releationship, an item relationship, and a quantity attribute. When you add Bread to a list, you actually add this 'link' object, and hook up the Item and List relationships, then set its quantity.

Many to many relationship with ADO.NET Entity Data Model

I've created many-to-many relationship with ADO.NET with extra order fields in the middle table.
So I have...
Customers
-customer_id
-customer_name
Orders
-order_id
Customers_to_Orders
-customer_id
-order_id
-seq
And now I don't really know how to add new orders to customers with specyfing order, any suggestions?
Create the order first.
Get the ID back for the order.
Then, create the link from the customer to the order.
you add the order to orders table first, and then add it to customer_to_orders preferably in one transaction.
if you're worried about the seq - it can be either identity or you can calculate "next seq" by querying customers_to_orders before adding new data.