Navigating by foreign keys in ADO.NET Entity Framework/MySQL - mysql

I am using ASP.NET MVC2 on top of a MySQL database in VS2008. I am using the MySQL ADO.NET connector 6.2.3 to provide the connection for the ADO.NET Entity Data Model.
This is mostly working ok, however navigating via foreign keys is causing me a real headache!
Here is a simplified example..
Car (Table)
CarID PK
Colour
Doors
ManufacturerID FK
Manufacturer (Table)
ManufacturerID PK
Name
In the edmx file I can see the 1-many relationship shown as a navigation property in the both the Car and Manufacturer tables. I create a Models.CarRepository that allows me to returns a IQueryable.
At the View I want to be able to display the Manufacturer.Name for each car. This is not accessible via the object I get returned.
What is best way to implement this? Have I encountered a limitation of the Entity Framework/MySQL combination?

Eager loading of the related records needs to be enabled in the Model Repository. Something like:
var allCars = from c in automobileEntites.Car.Include("Manufacturer")
select c;
This then makes the related records available for subsequent query/display.

Related

JPA JPQL - Query that returns if child object is not used (no primary key / foreign key relationship) and can be deleted

Spring Boot / MySQL / JPA / JPQL
I have an app that I would like to allow for the deletion of an object as long as it isn't being referend by another object (primary key / foreign key relationship)
For the UI I only want to show the delete button if there is no referential integrity issue/constraint (meaning if there is a pk/fk relation I don't want to show a delete button).
Let's say my child object is BookCategory and the parent object is Book. If a BookCategory is assigned to a Book then don't show the delete button, if there is no relationship then show the button.
Obviously in my case, BookCategory object model doesn't have a reference to Book, I could do that... but it seems a bit of resource waste, but maybe if I lazy load it wouldn't.
I'm trying to figure out a way through jpa / #query etc to allow for the UI to know whether to show the delete button or not.
I am looping through BookCategory(s) on the given page, but of course like I say it doesn't know if it is assigned to a book.
Seems like this thing would need to be done all the time, but not sure best how to build it.
Thanks, Keith
Suppose you have many to many connection between the entities.
In your example, you can use a lazy connection to the book and create an entity graph to load it when necessary or use jpql with join fetch.
You have to examine if there is a joined object or not, so you can also write a jpql to count the the joined object.
With Spring Data JPA you can create a composite model with, for example an id list, count... field refer to the books and put the other necessary fields for book category. Then spring data can load this into the model:
#Query(" select new com.mypackage.CustomBookCategory(b.name,count(b.book), ...) from BookCategory b where ...")
List<CustomBookCategory> findByCategory(String category);

Mapping SQL Views with NHibernate and Foreign Keys

In my Solution I have the following projects
MySystem.Core
MySystem.Core.Data
MySystem.MyAudit1.Core
MySystem.MyAudit1.Core.Data
MySystem.MyAudit2.Core
MySystem.MyAudit2.Core.Data
The number of audit projects could potentially grow to around 20.
The Audit projects all require an "Organisation" reference data table. Rather than duplicate the same reference data table across all audit projects 20 times and try to keep them in sync, my plan is to have a "master" organisation table in the Core project.
This will contain Code and Description for all organisations. Then, in each particular audit project have an OrganisationCode table that contains only the Org Codes relevant to that audit but not the description, and have a view in the audit database that looks up the description from the core Org table as follows:
CREATE VIEW Organisation AS
SELECT d.OrganisationCodeId as 'OrganisationId', d.Code, a.[Description]
FROM MyAudit1.dbo.OrganisationCode d
INNER JOIN [Core].dbo.OrganisationCode a ON d.Code = a.Code
This will mean that if Org descriptions change they can be updated in one place and reflected across all the audits.
However, as you cannot have foreign keys on Views within SQL I had created a foreign key between the OrganisationCode table and whichever other tables in the audit database needs them.
As I have discovered, this of course causes NHibernate to try and return OrganisationCode table rather than the Organisation view and causes my SessionFactory creation to fall over as Nhibernate is looking for OrganisationId in the OrganisationCode table.
Is there an easy way round this which will allow me to have a single description lookup in the core project for reference data that can be used across child projects
Yes the audit tables are spread over separate dbs, but I have got to the route of my problem.
The reason that my SessionFactory creation was falling over is that the Configuration was being passed the audit data assembly for mapping, and my organisation mapping file was in the core data assembly.
Now that I have solved that by adding an organisation mapping file in my audit data assembly, my trust object is returning the description values from the organisation view.
Thanks for looking.

Entity type not created for table with composite key

I'm using VS 2010, Entity Framework 4.3 and MySql.Data.Entity v6.3.5 to work with a MySQL DB with a couple dozen tables. I use the ADO.NET DbContext Generator.
Everything works well enough other than two tables don't get Entities created for them. Both have a similar structure in that they have a composite key composed of foreign keys to other tables. So, one is a region_flavor table that maps the (ice cream) flavors assigned to a particular sales region. It looks like so
region_flavor
-------------
RegionId INT(10) PK NN
Flavor VARCHAR(64) PK NN
RegionId is a FK to the regions table and Flavor is a FK to the ice_cream table.
There's another table with essentially the same situation.
When I do an "Update from Database", I see that there is, in the Model Browser, the table region_flavor listed under my IceCreamModel.Store\Tables / Views folder. But under my IceCreamModel\Entity Types folder there's no Entity Type.
I don't receive any .edmx errors when I do the update from the DB.
Perhaps I'm missing something here. Ideas?
I can post more info if that's helpful.
It is normal behavior. This is junction table used to model many-to-many relation in database. If it doesn't contain any additional column EF doesn't need to map it to entity because many-to-many relation is modeled directly and translated to table rows internally by EF.

How to synchronise Core Data relationships?

I'm creating an app that pulls data from a web server (MySQL), parses it and stores it in a SQLite database using Core Data.
The MySQL database has a 'words' table. Each word can be in a 'category'. So the words table has a field for 'category_id' to join the tables.
I'm having some trouble getting my head around how to replicate this locally in my app. I currently have entities matching the structure of the MySQL database, but no relationships. It seems like in my 'words' entity I shouldn't need the 'category_id' field (I should instead have a one-to-one 'category' relation set-up).
I'm confused as to how to keep this Core Data relationship in sync with the web server?
Assuming you have an Entity for Word and Category you will need to make a relationship (naming may be a bit hazy). Also assuming a Category can have many words and
// Word Entity
Relationship Destination Inverse
category Categories words
// Category Entity
Relationship Destination Inverse
words Word category // To-Many relationship
You are correct you would not need the category_id field as all relationships are managed through the object graph that Core Data maintains. You will still need a primary key like server_id (or similar) in each entity or you will have trouble updating/finding already saved objects.
This is how I deal with syncing data from an external database (I use RESTful interfaces with JSON but that does not really matter)
Grab the feed sorted by server_id
Get the primary keys (server_id) of all the objects in the feed
Perform a fetch using the a predicate like ... #"(serverId IN %#)", primaryKeys
which is sorted by the primary key.
Step through each array. If the fetch result has my record then I update it. If it does not then I insert a new one.
You would need to do this for both Word and Category
Next fetch all objects that form part of a relationship
Use the appropriate methods generated by core data for adding objects. e.g. something like `[myArticle addWords:[NSSet setWithObjects:word1, word2, word3, nil];
It's hard for me to test but this should give you a starting point?
Good to see a fellow Shiny course attendee using stack overflow - it's not just me

Define a one-to-one relationship with LinqToSQL

I'm playing around with LinqToSQL using an existing multi-lingual database, but I'm running into issues mapping a fairly important one-to-one relationship, so I suspect I am using the feature incorrectly for my database design.
Assume two tables, Category and CategoryDetail. Category contains the CategoryId (PK), ParentId and TemplateId. CategoryDetail contains the CategoryId (FK), LanguageId, Title and Description (in the appropriate language), with a combined PK of CategoryId and LanguageId.
If I drag-and-drop these tables into the LinqToSQL designer, the resultant object model has Category with a collection of CategoryDetail objects, which should never be the case. I'd like to be able to filter on LanguageId at the DataContext level, meaning that the whole Category is encapsulated within Category.CategoryDetail, not all language version encapsulated within Category.CategoryDetails.
This database worked fine on my old object library (an old-school custom BOL and DAL), but I fear that LinqToSQL would require this to change in order to give me the required result.
What is the best way to make this relationship (and language filtering) as seamless as possible?
You can view properties of the association. (Right click on the line representing the association and show properties.) The properties will tell you if it is a one-to-one or one-to-many relationship. This is reflected in code by having either a single entity association (one-to-one) or an entity set association (one-to-many).
I would have to assume cant be a true 1 to 1. Sounds like you have a PK of CatID and Lang ID on the Cat Details table. That would explain why its putting a collection. I could be wrong as you didnt mention the PK's of the CatDetails table
EDIT: A combined Pk of CatID and Lang ID makes that a 1:m relationship, and Linq to SQL is actually doing the correct thing. The only way it could possibly be a true 1:1 is if you had a lang ID on the cat table as well and that was part of the FK. I htink you may have to rethink what you want to do, or how you want to implement it.
I think LINQ to SQL models the database structure directly.
You have two tables so it creates 2 objects.
Have you had a look at LINQ to Entities this allows you to create another layer above the database strucure to make for more readable classes.
Since you don't have a 1:1 relationship the mapping alone will not provide the desired functionality. However it is easy to provide a method in the parent auto-generated class that does the job:
public partial class Category
{
public IEnumerable<CategoryDetail> GetDetailsByLanguage(string langID)
{
return this.CategoryDetails.Where(c => c.LangID == langID);
}
}