Entity Framework 4.0 Relationship map table - database

I have these tables;
Customer
- CustomerID (primary key)
- Name
Car
- CarID (primary key)
- Model
Customer_Car_Map (composite primary key CustomerID and CarID)
- CustomerID (foreign key to Customer.CustomerID)
- CarID (foreign key to Car.CarID)
When I generate the models from the database using EF4, it generates classes for all tables except for the _Map tables. For these it seems to add an EdmRelationshipAttribute, but not separate class.
How would I create and save a new Customer_Car_Map?

If the Entity Framework does its job correctly, you shouldn't need a class for the mapping tables.
Entity Framework 4 supports many to many relationships. It will generate Members on either of the Entities representing the two sides of the mapping tables. You will use the Entities to add relationships and Entity Framework will utilize the mapping table behind the scenes.
If those facilities aren't enough to get the job done, I would question why you need access to such low level data in your application.

Related

One to one relation using entity framework

I am working on a group project where an one on one relation in Entity framework is defined like this
builder.Entity<ApprovedAppointment>()
.HasOne(aa => aa.Appointment)
.WithOne(a => a.ApprovedAppointment)
.HasForeignKey<ApprovedAppointment>(a => a.ApprovedAppointmentId);
using fluent api. In the database the appointment primary key is the same as approvedAppointment primary key. For example, if appointmentId 5 is the first appointment to be accepted then the approvedAppointmentId is also 5 even though there are no other approvedAppointments inserted yet. Is this normal behaviour? Does anyone know why it works like this?
Yes, this the default mapping behaviour because you are pointing the FK at the PK of the table. You could remove the .HasForeignKey() altogether in that configuration.
The HasForeignkey() is available in EF Core to allow you to nominate a configured one-to-one relationship key in either of the tables to point at the PK of the other.
For example, you could put an "AppointmentId" in your ApprovedAppointment table, or an "ApprovedAppointmentId" in your Appointment table then map the ForeignKey accordingly:
.HasForeignKey<ApprovedAppointment>(aa => aa.AppointmentId);
or
.HasForeignKey<Appointment>(a => a.ApprovedAppointmentId);
respectively.
This would allow Appointment to have an AppointmentId of 5, while ApprovedAppointment's ApprovedAppointmentId is 1 or 2, but contains an AppointmentId FK of 5 to reference back to the Appointment.
Typically in a 1-to-1 relationship the two tables would just share the same PK to ensure the relationship is 1-to-1. With the alternate FK designated you are mapping either a 1-to-many or many-to-1 relationship that EF will enforce as 1-to-1. I'm not sure if EF Code First will set up a unique constraint on the FK column, but if not, you should add one to enforce it at a data level.

Mapping database structure from SQL Server to DynamoDB

I am thinking about using a NoSQL database to scale database reads. Please see the relational database structure below:
CREATE TABLE Person(
ID uniqueidentifier not null,
Name varchar(100),
DateOfBirth datetime)
CREATE TABLE Sport (
ID uniqueidentifier not null,
Description varchar(50)) -- e.g. Football; Tennis; Badminton etc
CREATE TABLE PersonPlaysSport (
PersonID uniqueidentifier FOREIGN KEY REFERENCES Person(ID),
SportID uniqueidentifier FOREIGN KEY REFERENCE Sport (ID),
primary key (PersonID, SportID)
In the example above a Person Plays many Sports. In my real application; I have many-to-many relationships like this that do not perform well.
How would these be stored in a NoSQL document database (DynamoDB)?
Disclaimer - I'm not familiar with DynamoDb, but have used several other NoSql databases
The common approach is to choose the most important subject entity as the root of the document (in your case, I would say this is Person)
A document is then created for each person, and will include the "person centric" view of all associated entities (i.e. linked sports):
Joe (Person, Keyed on a natural, or surrogate id).
+ Fields of Joe (Date of Birth, etc)
+ SportsPlayed: (Collection)
--> Golf (Sport)
--> Tennis (Sport)
If it becomes important to view the relationship from a Sport centric approach (e.g. you need to know which persons are 'subscribed' to which Sport):
You could attempt a secondary index on Person.Sport, if the NoSql database allows this. This would allow for queries like "Who plays Golf?", although this approach is often frowned upon in NoSql terms.
Alternatively, and preferably, create a second collection of documents, this time keyed by Sport:
Golf (Sport)
- Joe
- Jim
...
etc. Obviously there's extra work to be done in keeping both sets of documents up to date when a change is made to a Person, a Sport, or the relationship between them, however the benefit is high performance on the read side - only a single document needs to be retrieved to pull the entire entity graph - In SQL terms, this would have required a Query joining 3 distinct tables.

Separate tables for online and in-store purchases?

I'm developing a system for a retailer and I've hit a bit of a conundrum when it comes to deciding how to represent the orders in the database. The schema for my Order table so far is as follows:
Id - PK
AccountId - FK (Nullable)
ShippingAddressId - FK (Nullable)
BillingAddressId - FK (Nullable)
ShippingMethod - (Nullable)
Type - (Nullable)
Status
Date
SubTotal
Tax
Total
My problem is I'm not sure whether I should represent online purchases and in-store purcahses in separate tables or not. If I were to store them in the same table, all non-nullable fields would be the only ones applicable for in-store purchases.
Another design pattern that crossed my mind is something like this:
Online order table:
PurchaseId - PK, FK
AccountId - FK
ShippingAddressId - FK
BillingAddressId - FK
ShippingMethod
Type
Purchase table:
Id - PK
Status
Date
SubTotal
Tax
Total
And for in-store purchases, there would simply be no reference from the online orders table.
Thoughts?
I would make a second table for location, with a primary key and location information. That could be online as well. Then use a foriegn key in your main table. You would then just fill the fields require for the application you are doing(in store, or online). This would also allow For the business to grow to more locations just by simply adding it into the location table.
I'm going with the original design. Likely more maintainable and efficient as well.
Your second design is very close to an Entity Sub-typing pattern. If the primary key of your online order table was the foreign key to your purchase table then you would have entity sub-typing.
Your original design is a practical design for the physical implementation of your database because it is simple to use. Entity sub-typing would be the preferred design at the logical level because it clearly represents your rules about which predicates (columns) belong to which logical tables.
Some people would also use the entity sub-typing pattern for their physical model too because they have an aversion to nulls.

Entity Framework won't resolve PK-FK relationship with composite primary key?

I'm trying to set up an EDM on an existing SQL Server infrastructure, and came across a problem.
The EDM will not resolve a PK-FK relationship to a composite foreign key.
My DB table structure looks something like this (names changed to protect the innocent):
I have a PERSONS table containing an INT column called PerID (PK)
I have an OFFICE table containing an INT column called OffID (PK)
I am tying these tables together using a table called OFFICEPERSONS, creating a many-to-many relationship between PERSONS and OFFICE. This table has two INT columns, PerID and OffID, which together form a composite primary key.
I have a table called OFFICELOCATION that contains two INT columns, LocID and OffID. These two columns comprise a composite primary key. Additionally, OffID is also a FK to the OFFICE table.
Finally, I have a table called OFFICEPERSONSLOCATION. This table has three INT columns: PerID, OffID, and LocID. All three columns comprise a composite primary key. LocID and OffID provide a FK relationship to OFFICELOCATION, and OffID and PerID provide a FK relationship to OFFICEPERSONS.
With me so far? Hopefully, I haven't lost you yet. When all is said and done, my structure looks like this:
This structure works great in SQL Server. In EDM? Not so much. It will NOT allow me to construct the relation between OFFICEPERSONSLOCATION and OFFICEPERSONS. I get the following error:
Error 6037: Foreign key constraint 'FK_OFFICEPERSONSLOCATION_OFFICEPERSONS' has been omitted from the storage model. Column 'OffID' of table 'Model.Store.OFFICEPERSONSLOCATION' is a foreign key participating in multiple relationships. A one-to-one Entity Model will not validate since data inconsistency is possible.
Huh? Data inconsistency?!? How?
How do I get my entity framework to recognize this?
I agree that it is the entity framework's problem, and the problem is stupid. Even if you have the UPDATE CASCADE to "no action", it is not like you could create an inconsistency, but no, it claims that you can somehow.
In any case, in this situation, if you are willing to use surrogate keys instead of composite keys, you can get around this, because the only place to change the ID reference is in the main table.
In this case, OffID could be "inconsistent", but by using ID's in the OFFICEPERSONS and OFFICELOCATIONS tables (and therefore reference in OFFICEPERSONSLOCATION), you are forced to have the OffId managed in its primary table.

How can I use arrays of references in SQLite?

I am implementing a system to represent a school schedule in SQL, and I want to have a table called Student which includes all of the student's classes. do i need to include references to a Class table as attributes class1,class2,class3,...,class12
or can I use a sort of array?
Since you are using relational database, it would be good to make a m:n relationship between Student and Class table. It would mean that you will have Student table with primary key student_id, Class table with primary key class_id, and one more table, called StudentClass with foreign keys fk_student_id and fk_class_id, plus some additional properties (depending on what do you want to achieve). That would be a good relational design.
You could have a field filled with a comma separated list, or you could keep a separate table of 'allowed classes', with associated data (unique ID number, name, description, teacher), then use foreign keys and an intermediate table to implement a many to many relationship of students to classes.
Many to many relationship
Foreign keys in SQLite
Support for foreign keys in SQLite is pretty good these days, and all the features you'll likely want are there.

Resources