I have Products table and Customers table. Thus there is many to many relationship between them. This is my code to create that relationship using ModelBuilder:
modelBuilder.Entity<Customer>().
HasMany(c => c.ProductsPurchased).
WithMany(p => p.Customers).Map(m =>
m.MapLeftKey("CustomerId").
MapRightKey("ProductId").
ToTable("CustomersXProducts"));
Problem here is the Join table contains primary key of CustomerId and ProductId. This essentially means one customer can purchase the same product only one time. How can I resolve this issue? I don't want CustomerId to be a primary key in my join table.
You cannot resolve the issue with your database. You generally need some additional unique column to be primary key of your junction table or you need some addition data column to form composite key with both CustomerId and ProductId. That will lead to change in your model. You will need to expose junction table as an entity - Customer and Product entities must be related to the new entity.
Perhaps you will need this anyway. It is not very common to have such relation without any additional data. Perhaps your model needs bigger change. For example customer tracking system usually uses some form of entities like Customer, Order, OrderItem, Product so there is no relation between Customer and Product directly.
Related
I have the following Table Structure
Facility
PK Facility ID
AccountID
Accounts
PK NameID
PK AccountID
I can't touch the DB so my changes need to be in Entity Framework. Essentially the AccountIDs are linked so I want to create an association between them. So when I create an association I map the AccountIDs together, however I can't map FacilityID to anything and NameID to anything so when I save Visual Studio complains that the mapping is not set correctly.
My main question is how do I ignore the mappings for FacilityID and NameID? I've tried added [NotMapped] to both FacilityID and NameID but that does not work. I've also tried creating a scalar property for Facility and Accounts and used the Referntial Constraint to map them however when I try to map the columns under Table Mapping, the columns I added do not show up which causes VS to complain as well.
Here is my table, I removed most of the fields because they are unnecessary
Assuming Account.AccountID is unique (ie no two rows in Account actually have the same AccountID), just declare that as the only Key Property on the Account entity.
The Key of an entity does not have to be declared as the PK in the database. But you can only have one Key per entity (the Key can, of course, have multiple columns, and EF Core does support alternate keys). The entity Key should be unique, and should have a unique index in the database on the corresponding columns, but that's not enforced by EF.
Is it possible/or good practice to have one table like an address book that is related to different entities e.g: People, Companies, etc
I am thinking of using a compsite FK (typeid = entity type id e.g: 1 for people, 2 for companies etc, while the other column refers to the pk of the entity's table).
The other alternative I have is to use a junction table between the entities and address book table.
I am using VS 2005 C#, and sql server 2008
Assumption: your entities are all stored in one table with a type discriminator
Yes, a foreign key can have multiple columns.
An address entry only needs to know the PK of the parent entity
It does not need to know the type of entity: entityType is an attribute of entity not address
Junction table or straight FK? It depends on your relationships:
Can one address be shared by more than one entity?
Can one entity have more then one address?
Yes to both: junction table
Yes to Q1 only: address PK is an attribute of entity. Entity is the child table in the FK
Yes to Q2 only: entity PK is an attribute of address. Address is the child table in the FK
And the case I would not expect:
No to both: 1:1 relationship or you need only one table, address is an attribute of entity
I see no need for a type and an entity_id that refers to one table or the other. This is a complicated approach (two tables using the same ID pool and no foreign key to a table possible) that might cause problems later.
Your problem seems so simple that no tricks should be needed here.
You have companies, persons and addresses. If each person and each company has one address, you have the address id in the companies and persons tables. If a person can have more than one address you need a bridge table. Same for more than one address per company. That's all.
I've been used to this kind of convention before starting to work with Entity Framework/MVC:
tblMyItem (id, id_lookup1, val2, val3, val4...) - single, generic table
tblkLookup1 (id, val1, val2,...) - one to many relation table
tblmMyItemLookup2 (id, id_myitem, id_lookup2) - many to many relations table.
Recently I've found somewhere on the web that it's not good to create id column in tblmMyItemLookup2 when using Entity Framework, but I couldn't find more information on that. Could anyone please explain, why this is so significant?
When designing many-2-many relationship(i.e Student - Teacher) based on intermediate table (Student2Teacher) with only 2 foreign key columns, you'll end up having entities with navigation properties without intermediate table(no entity will be created for that table in context at all):
Student.Teachers <- EntityCollection<Teacher>
Teacher.Students <- EntityCollection<Student>
Meanwhile, if you add any extra field to your intermediate table, you'll have navigation properties pointing to intermediate entity:
Student.Student2Teacher
Teacher.Student2Teacher
making your querying uselessly more complex
In general we use lookup tables to macth associated records in two different tables that have a many to many relationship. For instance, let we have three tables: Students, Professors and StudentsProfessors. Since, a student can atten lesson that are serviced by many professors and a professor can teach more than one leasons then this is clearly a many to many relationship. So the lookup table called StudentsProfessors is used to match a student to her/his professors and vice versa. Now, the use of an id for each record of this lookup table is meaningless. We are not going to use this number anywhere. We just need to know that Student with studentId=10 is associated with professors with ids in (1,2,4,9). Just that and not the id of this record in the lookup table.
I've created an edmx for my database. In it Entity framework removed a table and instead created an association between two tables because it matches a column name with the primary key in the other table.
I do not want that as there is no real association between those tables. How can I remove that association and get a class for the middle table instead?
Example:
SomeTable
Id int pk
MiddleTable
SomeTableId int fk
SomeCode int
OtherTable
SomeCode int pk
It's the MiddleTable which do not get a class.
Remove one table from the edmx, e.g. OtherTable.
Update model from database and add MiddleTable.
Update model from database and add OtherTable.
When I do this with a similar model I end up with an association between SomeTable and MiddleTable and an unassociated OtherTable. Now you can add/remove associations manually as you wish.
It's normal EF behavior not to create a class for the middle table. This is a so-called many to many association between SomeTable and OtherTable which can be modelled by two collection properties:
SomeTable.OtherTables
OtherTable.SomeTables
The middle table, the junction table, is not really necessary.
It's a bit surprising to me that you say that there is no association between the two tables although, apparently, in the database there are foreign keys. Technically, it is a many to many association.
I have a database with multiple tables, and some basic relationships. Here is an example of the problem I am having:
My Database:
**Org**
ID
Name
etc
**Detail1**
ID
D1name
**Org_Detail1**
Org_ID
Detail1_ID
**Detail2**
ID
D2Name
**Org_Detail2**
Org_ID
Detial1_ID
BooleanField
My problem is, the Org_detail1 table is not showing up in the entity model, but the Org_Details2 table does.
I thought it may have been because the Org_Detail1 table only contains two ID fields that are both primary keys, while the Org_Details2 table contains 2 primary key ID fields as well as a boolean field.
If I add a dummy field to Org_detail1 and update it, it still won't show up and wont allow me to add a new entity relating to the Org_Detail1 table. The table won't even show up in the list, but it is listed under the tables.
Is there any solution to get this table to appear in my model?
Seems like I may just need to completely delete the model and recreate it. Adding dummy fields is the only solution I've found.
Not sure this is an MVC problem.
Does a Detail1 collection turn up in your Org entity and an Org collection show up in your Detail1 entity. This is the normal behaviour for Entity framework for a many to many intersecting table with no other tangible data.
If not then maybe the foreign key constraints are not defined.