I have Class and Student objects. Both have collection of another as property. Which automatically creates many to many table. Is there a way to add column to this table which relates to the relationship without creating many-to-many table by myself ?
No, there isn't. You have to promote the association table to an entity and have a one to many association to in on both Class and Student.
Yes it is possible, although really #Ricardo is technically correct really you should promote the join table to a fully qualified entity.
Some blogs posts that I have seen where people add extra properties to a many-to-many join table can be found here:-
http://thesoftwaresimpleton.blogspot.co.uk/2010/03/nhibernate-many-to-many-with-extra.html
http://nhforge.org/blogs/nhibernate/archive/2010/12/26/many-to-many-relationships-with-properties.aspx
http://www.thebuttonfactory.nl/?p=874
Google search turns up a lot (espically S.O. questions)
Related
I wrote a document imaging application in C# with SQL Server to catalog ancestor photos. In one table are all the ancestors and in another I am storing the photos along with information about the photo. Obviously, each ancestor can have one or more photos. This design is easy, I've setup a one to many relationship and it works great.
Here is the issue: how do I handle a photo that has multiple people in it? This seems like a many to one relationship except that the many would also be many.
What you describe is a many-to-many relationship. This is actually quite common.
It is usually solved with the help of an extra table.
So if you have Person and Photo, you create an extra table PersonPhoto.
This table contains (at least) two fields, PersonId and PhotoId.
No you define a one-to-many relationship from Person to PersonPhoto basied on PersonId and another one-to-many from Photo to PersonPhoto, based on PhotoId.
Efectively you now have a many-to-many relationship between Person and Photo: any photo can contain many people, and any person can be in many photos.
Got it! BJ, thanks for editing my initial post and not just deleting it. Much better.
oerkelens, thanks for the celerity.
I created the extra table with three fields: keyPersonID, keyLineNo and fldPhotoID. The keyLineNo provides the one-to-many along with the foreign key field for the person and a way to sort the results. I then used fldPhotoID for the one-to-one for my photos.
Once I saw your response it all made sense.
In EF cross reference tables are abstracted away by creating many-to-many relationships. E.G.
There's a SQL table dbo.TrialContactCrossReference that relates TrialContactId to TrialID. Now, EF did not generate an Entity TrialContactCrossReference because it went with this MANY-MANY relationship thing. How do I add a new row to said table?
I tried
context.TrialContacts.??? and context.ClinicalTrials.??? and just don't know what to do with this. If I have a new Contact that I want to relate to a trial how am I supposed to go about it?
trial.Contacts.Add(contact);
OR
contact.Trials.Add(trial);
OR (and my advise)
you could create an additional entity for cross reference table. this will convert many-many to 2 one-many relationships. more then %90 cases crosstables has additional columns (at least IsActive, RecordDate etc.) even it doesnt, it may be so in future and it requires you make lots of changes in code.
If I have a new Contact that I want to relate to a trial how am I supposed to go about it?
Assuming you have an existing Contact instance just do:
trial.TrialContacts.Add(contact);
context.SaveChanges();
EF will take care of the intermediate table insert for you. Note that adding Contacts and Trials works the same as if they weren't related.
There's a trick that was not obvious to me when setting this up. TableA must be added to TableB, not just to itself. In fact, looking at the generated entities each entity has a List<> of the other entity.
class TableA
{
List<TableB> TableB;
}
class TableB
{
List<TableA> TableA;
}
For example, if I want to add a TrialContact to a ClinicalTrial then I write:
context.ClinicalTrials.TrialContacts.Add(trialContact);
context.SaveChanges()
Then the xRef table be updated to reflect the relationship.
I am trying to come up with a database design that would work with Entity Framework 4 Code First. Actually, I have no experience yet of EF4 Code First but as I understand it, if I write the code, it will create the database and tables.
The issue is this. There are various types of auctions, they all have some common fields and some specific ones. In the code I envisage having a base abstract class called Auction and subclasses like LowestUniqueBidAuction and EnglishForwardAuction etc.
Nothing surprising there. The problem is that I imagine the database structure to mimic this. I imagine an Auction table and a LowestUniqueBidAuction table and a EnglishForwardAuction table. In the Auction table I imagine a foreign key into one of these two tables for each row depending on the type of auction that that row is. I also imagine another column in the Auction table with the name of the derived auction table (such as EnglishForwardAuction).
The problem is that whenever I've ever created a foreign key I've had to specify the name of the foreign table into which the key points (which makes sense). In this case, however, there is one of many tables that the key could point. So there are many issues here. Firstly, I could simply not use a foreign key and just use an ordinary field, but then the database will not be able to maintain data consistency for me. The second issue is how will EF Code First handle this? In other words, how will it know that if I ask for all EnglishForwardAuction rows from the Auction table that it should look at the column with the table name and then join on the EnglishForwardAuction table to get the extra fields?
Has anyone ever faced similar issues?
Thanks,
Sachin
This problem is solvable in Entity Framework in a number of ways - read up on how EF handles inheritance and what strategies are available.
There are basically three strategies how to handle this:
(1) Table per Hierarchy
You have only one single table, that represents all possible sub classes. Of course, this means, several rows (that only exist in a given subclass) must be nullable, since they don't show up / don't exist in super classes or other subclasses.
(2) Table per Type
Each subclass gets its own table, and by default, the sub-types table shares the PK with the base classes' table - e.g. PK = 1 in Auction will also be PK = 1 in EnglishForwardAuction. So your subclass tables reference the base table - not the other way around.
(3) Table per Concrete Type
Each concrete subclass (your separate auction types) gets its own table, but that table contains everything - all the columns, from that specific type, but also its base type.
Read more here:
Inheritance in the Entity Framework
Inheritance and Associations with Entity Framework Part 1
Entity Framework Modeling: Table Per Hierarchy Inheritance
Entity Framework Modeling: Table Per Type Inheritance
Searching for Entity Framework Inheritance and/or one of these strategies will reveal a lot more hits, too - that topic is very well covered and discussed on the interwebs! :-)
I have an entity that maps to a table called Rule. The table for this entity has an FK to another Table called Category. I'm trying to figure out how to pull in a property from Category in my Rule entity. I'm pretty sure I want to use a join in my entity mapping, but I can't figure out how to configure it so that it works. Here is my mapping:
Join("Category", x =>
{
x.Map(i => i.CategoryName, "Name");
x.KeyColumn("CategoryId");
x.Inverse();
});
Here is the SQL that it's generating...
SELECT ...
FROM Rule rules0_ left outer join Category rules0_1_ on rules0_.Id=rules0_1_.CategoryId
WHERE ...
Here is the SQL that I want.
SELECT ...
FROM Rule rules0_ left outer join Category rules0_1_ on rules0_.CategoryId=rules0_1_.Id
WHERE ...
I can't seem to find anything on the JoinPart that will let me do this. Subselect looks promising from the little bit of documentation I've found, but I can't find any examples of how to use it. Any advice on this problem would be much appreciated. Thanks!
"Join" is poorly named. a "join" in an NHibernate mapping implies a zero-to-one relationship based on a relation of the primary keys of the two tables. You would use a join if, for instance, you had a User table and a UserAdditionalInfo table, with zero or one record per User. The UserAdditionalInfo table would likely reference the PK from User as both a foreign key and its own primary key. This type of thing is common when a DBA has to religiously maintain a schema for a legacy app, but a newer app needs new fields for the same conceptual record.
What you actually need in your situation is a References relationship, where a record has a foreign key relationship to zero or one other records. You'd set it up fluently like so:
References(x=>Category)
.Column("CategoryId")
.Inverse()
.Cascade.None();
The problem with this is that Category must now be mapped; it is a separate entity which is now related to yours. Your options are to live with this model, to "flatten" it by making the entity reference private, changing the mapping to access the entity as such, and coding "pass-throughs" to the properties you want public, or by using a code tool like AutoMapper to project this deep domain model into a flat DTO at runtime for general use. They all have pros and cons.
Pardon the massive headline.
I'm in the situation of having to build an application on top of a database, that I cannot make any changes to. The database does not have any primary- or foreignkeys set.
I'm using linq-2-sql, and I'm interested in having some properties exposed on the entities generated from my dbml. For instance, in the hypothetical example of a one-to-many relationship between table education and student - where each student record has a reference to an education id, I'd like to be able to go:
var student = GetAStudentFromContextOrWhatever();
var studentsEducation = student.Education;
It is my experience, that this kind of property is automatically generated when I drag'n'drop tables with foreignkey relationships from the server explorer.
However as previously mentioned, in this case I do not have these foreign key relationships - rather I am adding the relationships manually in the dbml file, specifying parent and child class.
When I add these relationships, I expect the involved entities in the designer.cs of my context to get populated with properties of a kind like those described above.
This, however, does not happen.
What must I do for my dbml to create these properties for me - based on these manually mapped associations between entities/tables that, on a database level, do not have foreign key associations?
Cheers!
L2S is just that Linq-to-SQL. If it isn't in SQL it won't be generated. The expression trees behind L2S just can't understand what you are doing. The place for your association is in a partial class file which you will have create manually. Also it probably won't update or insert through the association.
I know this is a very old question, but I just ran into the same problem. In order for the relationship in the DBML designer to automatically create the association properties for you, you need to have primary keys on your objects. If you click the column name in the designer, you'll see that your PK field has PrimaryKey = false. Switch that to True and build; all should be well.
Patrick