I'm trying to understand Entity Framework Code First.
Is it possible to configure a many-to-many relationship without using fluent API but just DataAnnotation?
For example in this tutorial I don't understand if the two examples are the same thing but done in different ways or if they have to exist together.
If they are different ways for the same thing, what is actually the difference?
And if they have to coexist, what is the API "part" doing?
Indeed you are right.
This paragraph:
Configure Many-to-Many relationship using DataAnnotation:
Student class should have a collection navigation property for Course, and Course should have a collection navigation property for student,
is wrong. Because the many-to-many relationship in the sample code in created automatically by convention when you add a collection in each class. The only data annotation that is used is Required attribute which is not implied in the many-to-many relationship.
BTW the section about "Configure Many-to-Many relationship using Fluent API" is correct but in their sample code they use it only put a custom name to the foreign key in the join table instead of letting Code First generating it. Foreing key renaming can be done too with Data Annotation by using ForeignKey attribute.
They're two different ways of configuring the database. They can coexist, but they don't have to; you can use just one or the other. If you do use both, the Fluent API takes precedence over the data annotations, but the data annotations still take precedence over the default conventions.
The difference is that API allows a more exacting degree of control, in exchange for being (arguably) more complicated. The example you linked does show two different ways of accomplishing effectively the same thing, and you could use one or the other if you wanted to create that specific many-to-many relationship. But the API method would be more configurable if you wanted to do something odd with that CourseStudents (or StudentCourse) table, while the annotation method would be more limited but is easier to read at a glance if you don't need the extra functionality.
Related
In my application, I have an entity, say Customer which maps to Customer. This is working fine now.
Our plan is to provide our current project as a reference to another client project. The client project also has a Customer table, but with some additional columns. Creating another Customer entity in the client project throws the error saying "both types have simple names".
Can this be solved using inheritance. Or does EF allow us to create classes with different names and map it to same table, like Customer and CustomerClient both maps to Customer table, but CustomerClient has the additional columns added.
Edit: I will try to provide the code once I am in office.
It sounds like entity framework inheritance is what you are looking for,
and especially TPH (Table Per Hierarchy) which is the the way to implement inheritance in entity frameork where all derived entities mapped to the same table.
TPT (Table Per Type) is the other option where all dervied classes are mapped to their own tables beside the base class table.
If you are looking for more info about implementing TPH and you are using EF code first this a good link to start with, and if you are using the designer you can use this.
Here is a tutorial how to choose EF inheritance strategy.
Note: I did not mention the TPC (Table Per Concrete Class) strategy which is also described in this post becuase I do not think this is what you are looking for.
This is a great video lessons tutorials that cover EF inheritance using code first and the designer and much much more.
Hope it helps!
In my asp app I want to use something like Polymorphic association from Ruby on Rails' Active record in Entity Framework.
I know there are some topics already on StackOverflow discussing this, but I want to achieve it without using of inheritance as it is able in ruby on rails, so I want to ask if it is possible.
Thank you.
Ruby on Rails implements this pattern by defining a type and a key column. As it says in the link you quote:
To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface
In a canonical relational database this can never be implemented as a foreign key constraint, because one foreign key field can only refer to one primary key field. So a polymorphic association in RoR probably implemented merely as a "soft" foreign key.
That's the reason why this can't be done in EF exactly as it is done in RoR. Same as a foreign key, an association can only refer to one other entity. However, you can create inherited classes, each of which can refer to their own entity. That's why you will only find examples of inheritance when these associations are implemented with EF. Another example is my question here.
I have a lot of experience of doing proper polymorphic associations (i.e. associations defined by an interface, not by an abstract type) using Entity Framework. I think this pattern is essential for good object modelling, and I have berated the EF development team several times about the lack of native support for this pattern which could easily be added, IMO. (Native support would include the ability to query those associations in LINQ to Entites, just as you can in LINQ To Objects).
In my implementations, you have to hold a 'compound key' that defines the type and the identity of the associated objects - which, I believe, is how it is done in both Hibernate and RoR. Navigating the relationship is done in code, by reading this key and then dynamically creating a method for accessing instances of the corresponding type.
Although you cannot make this compound key an FK, you can add referential integrity with a bit more effort using the 'table of two halves pattern'. I have written this up in some detail in the Naked Objects Development manual, which you can look up on Git Hub. The patterns do not depend upon the Naked Objects Framework, however, and you could replicate them. All the source is there (see the class PolymorphicNavigator in NakedObjects.Helpers).
Further to #richard-pawson's answer, I've ported the "table-of-two-halves" pattern from Entity Framework to Java (JDO/DataNucleus), with a complete example up on github.
You should be able to use it to come up with something similar back in .NET land.
My model turns my join tables into a many-to-many relationship in the model editor. This means that when I query a table through the many-to-many relationship to a row in the other table, I get the EntityCollection instead of IQueryable.
It is my understanding that it is more efficient to stick with IQueryable because EntityCollection loads instances of the entity classes into memory then queries those.
I'm not sure it's exactly what you're looking for, but EntityCollection<T>.CreateSourceQuery() will return a new instance of ObjectQuery, which implements IQueryable<T>.
Check out http://www.asp.net/entity-framework/tutorials/creating-a-more-complex-data-model-for-an-asp-net-mvc-application and look in the Customizing the Database Context section. There is a fluent API example of how to use join tables on many-to-many relationships. When I have a DB already defined, I like to create my own model classes and use Fluent API and Data Annotations to link them to the appropriate tables. That way I control how the application uses those tables instead of trusting the framework to build the way it thinks it needs to be built. This does two things: 1) It ensures that you are familiar with how the app uses your data, and 2) gives you more control over how data is represented in the app.
Happy coding!
OK,
This is probably not simple but I figured I would throw it out there:
I get the idea of extending an Model-First entity in EF with a partial class to add data annotation elements somthing like this:
[Required]
string MyString {get;set;}
However, if I am in a multi-tenant system where I may want to customize which fields are actually required when passed to the end client can I dynamically set the annotation depending on how the client has configured the setting, say in another table for instance?
Update: In the multi-tenant system there are at least two databases. One that stores system configuration information. In addition each customer would have their own individual database. The system DB controls routing and selecting the proper customer database from there.
Any insights or ideas anyone has on how to accomplish this would be great!
Thanks,
Brent
If you are using EF 4.1, you could create different DbContexts, referencing the same entities, but provide different mappings using the Fluent Api.
Here is a link to a video that describes using the api.
Fluent Api
Note: Your database would need to be setup to accommodate all the different configurations. For example, if in one context, "FirstName" is required, and in another it is not, your db should allow NULL in order to cope with both situations.
You can't change attributes dynamically.
One option would be to crate the types dynamically, probably inheriting some class (or implementing an interface), that you actually work with. Although I'm not sure this would work with EF.
Another possibility is if EF had another way you could tell it the same thing, but I don't know EF much, so I can't tell if something like that exists.
I have created an EF4 CTP5 based code first model that includes two entities in a parent-child relationship where the child entity contains several extra fields. Both types are derived from the same table TPH and use a newly created discriminator. Now, I need to figure out how to expose the child entityset via the data service and make it available for querying.
The use-case for this is that we have a table that contains a hierarchy of clients. Each client has a parent and zero or more children. A parent contains just the information needed to set-up the client and for billing (name, address, etc.). The children (you can think of them as sattelite branches) contain an additional set of properties that are unique to them in addition to what they inherit from the parent. All are contained in the same table that has been denormalized for pure search performance.
So far, I have exposed the entity set in the manner suggested in this blog post It suggests exposing a method that returns the context.Child IQueryable collection. However, this entity set is way too large (700k+ records) to just expose the entire thing and I cannot seem to get standard oData queries to work against the service operation.
My questions are numerous but to keep this post as concise as possible I will limit them.
•First, I want to know if this is still the best and only way to handle this? It seems like not allowing derived types to be exposed without this workaround is a major gap in functionality.
•Second, how can I query this entityset? Is this possible? Is it possible I do not have something materialized properly in the EF piece?
Any and all help or suggestions are greatly appreciated.
Best and thanks in advance!