Many to many relationship with ADO.NET Entity Data Model - ado.net

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.

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.

Manually creating intermediate table in a many to many relationship for Core - Data

I'm currenty working with Core-data for an iPhone project.
But I'm a bit confused about one element.
With Core Data currently you do not need to create the intermediate table when creating many to many relationships (its all handled behind the scenes by core data)
But in my case I actually need some attributes on my many to many relationship!
For example
I have a table called Students
and another table called Lessons
a Student can be in many lessons
and a lesson can have many students
Now a standard many to many relationship will not work for me as I actually need to define more details on the join, i.e. StartDate and LeaveDate.
In a standard sql model for example my join table would be something like
StudentLessons (Studentid, LessonId, StartDate, LeaveDate )
I would need these properties as when i'm querying for information I will need the details from the join to filter my results.
How can I create this in core data and also filter for results?
I've seen folks say that you would actually create the StudentLesson entity manually in core data.
Now if I did this would I just have the attributes (Startdate, LeaveDate) and then a one to many relationship from the Student and then the Lessons table?
Student - > StudentLessons
Lesson - > StudentLessons
I guess I'm a bit confused on how I would go about making sure that the relationships and the content of the relationships are setup correctly. (i.e If I add an Student object to the StudentLessons - how would I then assign/add the Lesson.)
Sorry this is my first time playing with Core Data.
Takes a bit o getting used to when coming from a full on sql background.
You are absolutely right. The correct way to do this is to create a new entity like StudentLessons. Let's call it Attendance. It should have the startDate and endDate, and two relationships.
The relationship to the student can be many-to-many, unless it is foreseeable that startDate and endDate are always different for each student. One Attendance with its dates can have many students in it. One student can have several Attendance duties.
Student <<---->> Attendance
Clearly, the relationship to Lesson should be one-to-many. One Lesson can have different Attendance configurations, with different dates. But each Attendance belongs only to one Lesson.
Lesson <---->> Attendance
To address your question, you can make the Attendance attribute of Lesson non-optional (and vice versa), this way it will ensure that each Lesson has at least one Attendance with appropriate dates, and each Attendance has exactly one Lesson.
I think your can remove the link between Student and Lesson. Just assign an Attendance rather than a lesson. If you want a Lesson assigned to a Student without dates, just allow Attendance to have NULL as those properties.
TheTiger,
Just because Core Data will create a join table for you, that doesn't mean you have to use it. Maintaining which student succeeds with which lesson is just the same except you will create the intermediate entity and then use the appropriate setters to build the relationships.
You will have to use more key paths and do relationship prefetching but those are straightforward to do.
Andrew

Trouble inheriting from another entity

I'm having trouble configuring entity relationships when one entity inherits from another. I'm new to ADO Entity Framework -- perhaps someone more experienced has some tips for how this is best done. I'm using .net 4.
Database tables with fields:
Products (int ID, nvarchar Description)
FoodProducts (int ProductID, bit IsHuge)
Flavors (int ID, int FoodProductID, nvarchar Description)
There are constraints between Products and FoodProducts as well as FoodProducts and Flavors.
Using the designer I create a model from the database. The designer seems to get it right, with a 1:0..1 association between Product and FoodProduct entities, and 1:* association between Flavor and FoodProduct. No errors when I save or build.
Next I set FoodProduct entity to inherit from Product entity. Then I get errors concerning relationship between Product and FoodProduct. Ok, starting fresh, I first delete the relationship between Product and FoodProduct before setting the inheritance. But now I get errors about the relationship between FoodProduct and Flavor. So I delete and then recreate that relationship, connecting Flavor.ID to FoodProduct.ProductID. Now I get other errors.
My question is this: Should I instead be creating relationship between Flavor.FoodProductID and Product.ID? If so, I assume I then could (or should) delete the FoodProduct.ProductID property. Since my database will have many of these types of relationships, am I better off first creating the entity model and exporting the tables to SQL, or importing the database schema and then making many tweaks?
My intent is that there will be several types of products, some of which require many additional fields, some of which do not. So there may be zero or one FoodProducts records associated with each Product record. At least by my thinking, the table for each sub-type (FoodProducts) should be able to "borrow" the primary key from Products (as a FK) to uniquely identify each of its records.
You can find a screen capture here: http://img218.imageshack.us/img218/9720/entityframework.jpg (I'd embed the img but haven't earned the requisite rep' yet!)
Well, I deleted the FoodProduct.ProductID field, as it should always return the same value as Product.ID anyway. Then, as you hinted, I had to manually map the Products.ID field to FoodProducts.ProductID field. Errors resolved. I'll write a little code to test functionality. Thanks for the "observations"!
Couple of observations:
FoodProducts needs a primary key (e,g identity - FoodProductID). Are you sure it should be a 1:0..1 between Food and FoodProducts? I would have thought it should be 1:0..*. For this cardinality to work you need a unique PK on this table.
When you setup inheritance for entities, the parent entity's properties are inherited. So FoodProducts will inherit ID from the Product table.
BUT, on the physical model (database), this field still needs to be mapped to a column on the FoodProducts table - which is why you need the identity field.
After you setup inheritance, you still need to map all the columns on the derived tables. My money is on you have not mapped "ID" on FoodProducts to any column.
If you screencapped your model and show the errors you are getting it would be much easier to diagnose the issue.

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. :)

Can't insert entries of a many-to-many relationship in Entity Framework in a specific order

I have a many-to-many relationship between 2 entities in Entity Framework, like here . So, Employees and Projects. At one point, I would like to insert some Projects to a Employees entity in a specific order. By conserving the order I would like to know which was the first preference of the Employees for a Projects entity. The thing is that although I order the Student.Projectslist in the way I like before the insert, when selecting Employees.Projects.FirstOrDefault(), the entities are ordered after the ProjectsId and I don't get the first element I inserted. How can I conserve the order I want?
O course, I could make a new field PreferredProjects and save the other Projects in a random order, since only the preferred one is important for me. But this is not an option, being given the context of the current project's software design.
Thank you in advance...
It sounds like you simply want to have sorted child collection results when you do a query, rather than take full control of the insert order.
You can achieve that using the techniques described in Tip 1 of my tips series.
Hope this helps.
Alex
Program Manager Entity Framework Team.
Unfortunately, there is no easy solution. I have the same problem. The only solution is to save after adding each child item (project). This is the only way to save the order without using a new field column to sort input.
Try Employees.Projects.OrderBy(x => x).FirstOrDefault()