unwanted column in entityframework database - c#

I am working on an MVC project in Visual Studio Ultimate 2013 and I have some unwanted columns in some of my tables and I cannot really understand why is it so.
In table Categories there is the column Template_TemplateId which is probably because in the Template entity class there is a ICollection<Category> property.
I want a Template to have many categories, however a one category can be repeatedly used by many Templates so I guess the Template_TemplateId column is something I don't want there.
Can someone explain, why is this so, and what should be a right approach to have the model the way I want it?
Thank you.

Model First:
Be default, EntityFramework creates one-to-many type relationships. When you create those, you need a foreign key in the "one" side of the relationship.
This is the "Template_TemplateID" field. It is the foreign key into the "Templates" category. However, you said you wanted a many-to-many relationship, so you are absolutely right; that field is useless!
You need to specify a cardinality of "*" on both ends of the relationship, then the model will create an intermediate table allowing the many-to-many relationship. The foreign key should go away at this point.
Code First:
Same problem, but the solution is to make a collection of "Template" in categories and and a collection of "Category" in templates, thus creating the many-to-many relationship.

If you want a many-to-many relationship between Templates and Categories create two collections, on on each class - on Template, create a ICollection and on Category, create ICollection.

Related

Entity Framework Navigation Property for a field that can store a foreign key from two different tables

I need a table called Loan.
The columns of this table will be:
Id, Type, BorrowId, Description
The trick here is that Type field will determine whether the borrower is an Employee or a Customer and then the BorrowerId will either be an Id from the Employee table or an Id from the Customer table.
Is this bad design as far as Entity Framework is concerned? The reason I ask is because it seems like I won't be able to create a Borrower Navigation property on the Loan table since the Id can be from two tables.
Does anyone have a solution for this? Like how I can change my data models to work with Navigation properties.
A simple answer to your question is "Yes it's a bad design". Referential Integrity should be strictly enforced and when you remove that ability by alternating the reference you create a window for errors. If you want two options create two columns, and create foreign keys on each to the tables they reference. Then your application will be effectively foolproof. :D

Adding a property to an association

Having two tables Courses and Employees, i have a many to many relationship between the two. EF automatically generates an intermediary table called CoursesEmployees.
I want to add a property IsPassed to that intermediary.
I could do this in MySQL but i won't know where to map it to in my data model. Is it possible? Preferably in the data model because i work model-first.
I use all of the latest versions.
The way to achieve what you want in a Model First approach is to explicitly model the relation table and add your IsPassedproperty to it, as I've done below. There is a 1-to-m relationship between Course and Course_Employee entities as well as a 1-to-n relationship between Employee and Course_Employee entities. The combination of the two one-to-many relationships creates the many-to-many relationship between Course and Employee entities.

One-to-one self-relationship and Entity Framework

I would like to have entity which can have a child (one or zero). This child is same type as parent. I am not sure how to set entity framework becouse I would like to have two navigation properties for every entity. One for navigation to child and one for navigation to parent. Basically it is exactly the same structure as doubly linked list.
I think this table structure should be enough:
int | id | PK
int | id_next | FK
text | data
But how can I create navigation properties for next/prev items? I am able to create only navigation property for next item.
Thanks for help.
You can't. The problem here is that a one-to-one relation has a very specific requirement - FK value must be unique in the whole table. Once the uniqueness is not enforced you can add a second entity pointing to the same parent and you have a one-to-many relation.
To enforce this in a self referencing relation like you described in your example you will place an unique index on the id_next and it will work in SQL server. The problem is that entity framework doesn't support unique keys. Because of that entity framework is only able to build one-to-one relations between two different entity types where FK in the dependent the entity type is also its PK (the only way how to force FK to be unique) = both entities has same PK value. This cannot work with a self referencing relation because you cannot have two same PK values in one table.
You can do this in EF4 by specifying a 0..1 -> 0..1 relationship on the entity. Name one of the navigation properties "Previous" and the other "Next". This will create a hidden field on the underlying DB.
I haven't thoroughly tested this approach but it seemed to work when I created the database script.
Research Tree structures in the Entity Framework. You basically want a vertical tree (i.e. one branch). The framework won't enforce only one branch, but you can manage that in your business logic.

Inheritance of database tables in VS

I want to create Table-Per-Type database table inheritance.
Simply base table RowElement will have 2 children tables. First child table Lyrics will inherit all parents RowElement's columns and will just add one more column. Second child table ChordUse will only many-to-one relationship to table Chord.
This is how my database schema looks like:
alt text http://www.freeimagehosting.net/uploads/ae4d8bd348.jpg
The problem is that when I let the VS create E/R diagram for me it creates this:
alt text http://www.freeimagehosting.net/uploads/774b194451.jpg
So it creates an 1-to-1-0 entity relationship instead of inheritance. I can't get VS to create inheritance relationship mapped correctly to database. Please help me.
After generating E/R diagram from my database I would like to have something like:
alt text http://www.freeimagehosting.net/uploads/e532f09b8a.jpg
Where RowElement is abstract class. Thank you for any help.
The EF designer (for good reasons, IMHO -- inheritance is overused in OR models) will never infer inheritance. You need to set it up yourself. You are asking for "table per type" inheritance. Follow the walkthrough with the demo model. When you've got that working, you'll be ready to do it with your real model.

LINQ many-to-many relationships: Solution?

LINQ so far has been remarkably elegant, but to perform basic m2m queries it offers no solution I can imediately see.
What's worse is that while it works for any other table relationship, LINQ is not giving me an association in the class structure for my m2m table.
So I can do things like
artwork.artists.where(...)
//or
artist.Artworks.add(artwork)
but I can't do
artwork.artowrks_subjects.tagSubjects.where(...)
//or
tagSubject.artworks_subjects.add(artwork)
alt text http://img299.imageshack.us/img299/257/20090902122107.png
Is there a common pattern for solving this limitation?
the way I have gotten M2M working in LINQ2SQL:
drag the tables into the builder,
like you're showing in the question
remove the relationship between
artworks_subject and artwork
create a new relationship FROM
artworks_subject TO artwork
click on the new relationship to get
its properties
change the
cardinality from OneToMany to
OneToOne (because ManyToOne doesn't
exist)
open the Child Property
section and change the Name field to
make it singular (Artworks to
Artwork)
now the tagSubject entity will have a collection of artwork_subjects, and the artwork_subject will have a property of type artwork called Artwork. so you can now make a LINQ expression like
var x = dbcontext.tagSubjects.Single(s=>s.name=="Landscape").
Artwork_Subjects.
Select(as=>as.Artwork.Name);
Found the solution myself. For automated relationships to work, both tables need primary keys (oops). Notice artworks_subjects is missing the PK symbol.
This largely depends on what framework you are using. It sounds like you are using LINQ-to-SQL, which is very literal about tables to objects. With Entity Framework, there is inbuilt support for many-to-many, in particular for the trivial case you've listed (a linking table with no additional properties). EF will generally spot this pattern, and hide the link table from the conceptual model (I can't remember, but it might need a spanning PK over the two FK columns).
Of course, this then goes sour if you want to add columns to the link-table; so in some ways I'd be tempted to leave it "as is".
With regards the where etc - how do you mean? You can do joins over the association, and you should be able to use Any etc; do you have a concrete example of what you want to do?
Yes. Instead of many-to-many use two many-to-one relationships:
Subject -*----1- ArtworkSubjectParticipation -1----*- Artwork

Categories