How to Add a Many-To-Many Relation in Entity Framework - vb.net

I am a newbie. I have been able to Add new entities where there is a One-To-Many Relation. I am having a problem (don't Know how to do it) adding a new Entity when the relation is using Many-To-Many.
In my EDM I have:
Orgs
<Scalar Properties>
a. Org_ID (Identity Field)
b. OrgName
c. OrgDesc
<Navigation Properties>
Building_orgs_Relation
Buildings
<Scalar Properties>
a) Building_ID (Identity Field)
b) Building_Desc
<Navigation Properties>
Building_orgs_Relation
Org_Building_Relation
a) Building_org_ID (Identity Field)
b) Org_ID
c) Building_ID
<Navigation Properties>
Building
Org
I want to:
Insert New Orgs
Delete Existing Org
Reassign Org To different Building
Update Org
Can some please provide a sample on how to do it using the mentioned EDM?
VB code will be appreciated.

Right now, the Entity Framework is really limited in terms of what kind of many to many relationships it can handle. The only thing that the Visual Studio designer will recognize is a table consisting of only two columns, both foreign keys to the other two tables, and where the primary key is a compound key on both of the foreign keys.
So, if you have control of your database schema, one thing you could do is change your Org_Building_Relation table to drop the Building_org_ID column and make the primary key a compound key on Org_ID and Building_ID. If you do that, then when you map the tables the Entity Framework will recognize this as a many to many relationship.
If you can't do that (e.g., you don't have control of the database schema), then you will need to make sure that the only fields that you map in your EDMX are the fields which relate to the other tables, and that you do not map the primary key. This is difficult, because the mapping wizard will discard and re-create the storage mapping every time you update.
Another option would be to not use a "proper" many to many mapping in the Entity Framework and instead just treat the relationship as another entity instead of having it subsumed into the relationship.
I can't remember if this has been improved in the forthcoming .NET 4.0.

Related

Questionable SQL Relationship

I am going through a pluralsight course that is currently going through building an MVC application using an entity framework code-first approach. I was confused about the Database schema used for the project.
As you can see, the relationship between Securities and it's relating tables seems to be one-to-one, but the confusion comes when I realize there is no foreign key to relate the two sub-tables and they they appear to share the same primary key column.
The video before made the Securities model class abstract in order for the "Stock" and "MutualFund" model classes to inherit from it and contain all relating data. To me however, it seems that same thing could be done using a couple of foreign keys.
I guess my question is does this method of linking tables serve any useful purpose in SQL or EF? It seems to me in order to create a new record for one table, all tables would need a new record which is where I really get confused.
In ORM and EF terminology, this setup is referred to as the "Table per Type" inheritance paradigm, where there is a table per subclass, a base class table, and the primary key is shared between the subclasses and the base class.
e.g. In this case, Securities_Stock and Securities_MutualFund are two subclasses of the Securities base class / table (possibly abstract).
The relationship will be 0..1 (subclass) to 1 (base class) - i.e. only one of the records in Securities_MutualFund or Securities_Stock will exist for each base table Securities row.
There's also often a discriminator column on the base table to indicate which subclass table to join to, but that doesn't seem to be the case here.
It is also common to enforce referential integrity between the subclasses to the base table with a foreign key.
To answer your question, the reason why there's no FK between the two subclass instance tables is because each instance (with a unique Id) will only ever be in ONE of the sub class tables - it is NOT possible for the same Security to be both a mutual fund and a share.
You are right, in order for a new concrete Security record to be added, a row is needed in both the base Securities Table (must be inserted first, as their are FK's from the subclass tables to the base table), and then a row is inserted into one of the subclass tables, with the rest of the 'specific' data.
If a Foreign Key was added between Stock and Mutual Fund, it would be impossible to insert new rows into the tables.
The full pattern often looks like this:
CREATE TABLE BaseTable
(
Id INT PRIMARY KEY, -- Can also be Identity
... Common columns here
Discriminator, -- Type usually has a small range, so `INT` or `CHAR` are common
);
CREATE TABLE SubClassTable
(
Id INT PRIMARY KEY, -- Not identity, must be manually inserted
-- Specialized SubClass columns here
FOREIGN KEY (Id) REFERENCES BaseTable(Id)
);

obtaining foreign key from DEPENDENT possibility in create table SQL

Lets say you have two entity named Parent and Child.
Child entity is DEPENDENT of Parent entity.
A weak key of child entity is the NAMEOFCHILD.
Is it possible for the Parent entity to have NAMEOFCHILD as a foreign key?
This idea has not been talked about in class. I was wondering is this possible in SQL?
If so, should i just add
FOREIGN KEY (NAMEOFCHILD) source CHILD
in my table?
In the database schema, yes (if Child.NAMEOFCHILD has a unique index). In entity framework, no. EF doesn't support associations to unique indexes (yet). But this is just on the technical level. Whether it's meaningful is another question.
Also, beware of painting yourself in a corner. When both foreign keys are not nullable you'd never be able to insert data, because you can't insert two records at a time and sequential inserts always cause foreign key violations. You would be able to design the database schema but never get any data in.

Entity Framework: One to Many relationship

I have a design problem with regards to Entity Framework model relationship
I have this model in the edmx
Business Rule:
A Participant can have multiple Roles so I create a relationship table ParticipantRoles that has 1-to-Many relationship on the Participant and the Role table
The Problem:
In order to get the Participant's Role value, I have to drill down through Participant->ParticipantRole->Role (see JSON output below)
The Question:
In EF, how to design the table relationship to bypass the ParticipantsRole table. I want to access the Role in something like this Particant.Role and not Participant.ParticipantsRole.Role
You say A Participant can have multiple Roles. And of course, a Role can have multiple Participants. So basically this is a many-to-many association.
Entity Framework will only map pure many-to-many associations (without connecting class) when the junction table only has two foreign keys. In your case, if the table ParticipantsRole only would have had a primary key consisting of ParticipantId and RoleId at the time of generating the model the class ParticipantsRole would not have been created. You would have had Participant.Roles and Role.Participants as navigation properties.
However, the model has been generated with ParticipantsRole and you want to get rid of it. (Or not, I'll get back to that).
This is what you can do:
Remove ParticipantRoles from the class diagram.
Modify the database table ParticipantRoles so it only has the two FK columns, that both form the primary key.
Update the model from the database and select ParticipantsRole in the Add tab.
This should give you a model with a pure many-to-many association.
However, think twice before you do this. M2m associations have a way of evolving into 1-m-1association (as you've got now). The reason is that sooner or later the need is felt to record data about the association, so the junction table must have more fields and stops being a pure junction table. In your case I can imagine that one day participant's roles must have a fixed order, or one marked as default. It can be a major overhaul to change a m2m association into 1-m-1 in a production environment. - Something to consider...

Fluent Nhibernate mapping Legacy DB with composite key

I am using Fluent NHibernate (which I am fairly new to) in an application I am developing using a legacy Oracle DB. The DB has composite keys which are comprised of foreign keys and database generated columns. The generated columns are supplied by calling a DB function with the table name, and one of the other foreign key parts. The generated composite key parts are not unique, and I cannot change this. The generated key parts are often used as foreign keys on other tables too.
If I create entity mapping which specifies the composite key as it is in the database, then we cannot use any identity generation strategies, which breaks unit of work
If I create entity mapping which specifies only the generated column as the primary key, then I can use trigger-identity to generate the ids, and I get unit of work, but I then have a problem when I want to update, or access a child collection: The other parts of the key are not included in the WHERE statement.
Can anyone give me any advice on how to proceed?
If I stick with mapping composite keys, can I extend nhibernate to output the SQL to use trigger-identity? If so, can you suggest a starting point?
If I map a single column key, can I include other properties in a WHERE clause for HasMany mapping and Updates?
Unfortunately, as you have already found out, there is no support at all for this setup.
My suggestion is to do INSERTS manually (using custom SQL, for example). And yes, this breaks the UoW, but that is true of identity too.

Make a one to Many relationship in ios using core data

I have two models :
Card with has_many relation to Works
I mean i have 7 static works in my database and i can choose some of them when i create a Card.
I defined a has_many relationship like this :
My problem is strange... it seems to work, but when i explore my sqlite file, i don't see any table relationship between Card and Work.
I am expecting a table with card_id and work_id.
How core data store has many relationship?
Firstly, I'd caution you from opening up the sqlite files Core Data spits out and trying to infer things from them. It's meant to be an opaque format: you're only supposed to interact with Core Data persistent stores through the Core Data APIs.
However, to answer your question: in general in database design, you wouldn't use a linking table like you describe for a one-to-many relationship, only for a many-to-many. For a one-to-many, you'd have a foreign key field in the table at the 'one' end, and have the contents of that field be the primary key of another table. For example (sorry for the random example I found on Google):
tblOrder is in a one-to-many relationship with tblOrderDetails. This is implemented by having an Order# field in the to-many side of the relationship, which is a foreign key referring to the primary key of the tblOrder table. As you can see, no linking table is needed.
A many-to-many relationship would need a linking table, but a one-to-many does not.
One final point: I note in your screenshot that you don't have an inverse relationship set up for your works or customer relationships. Core Data requires all relationships to have an inverse, otherwise your data may become corrupted. (That's somewhat a simplification, since there are other ways to work around it, but in general making inverses is easiest.)