How do I get the column name from an Entity Framework Association - entity-framework

I have an entity model built using the designer. In one of my tables (application), I have several foreign keys that reference the same status (status) table. As a result, when my associations were built, I have several entity objects built with an auto indexing name:
application_statuses2
application_statuses3
etc.
I'm building a "version history" type screen and want to be able to properly list the "friendly name" for each column modified. For example, I want to display "Destination Status" will be displayed instead of "application_statuses2". If I can determine the endpoint column name on the association in question, I can setup the proper display value.
I can find the entity object in the designer, I can even track where it references the foreign key in question that built the association, but I can seem to find the property that outlines the enpoints or column names. How do I determine the column name, or endpoint, on my association, or entity?

I wish it were more ready to hand, have been looking for it as well. Bit of a pain when you have multiple FKs to the same table.
Click on the navigation property you want to check
Under properties, look at the name of the association
At the top of properties, use the object navigator dropdown to switch to the association
Click into the 'Referential Constraint' property
Use the ellipses button on the right to bring up the column names
Dont know if there is a better way of doing this, but I certainly hope so!

Related

Symfony2: Collection of dropdown select lists for a many-to-many relationship

The objective:
Having a many-to-many relation be displayed as a dynamic list of select inputs(single choice dropdown list)
User arrives on page with a single select field (multiple = false) populated with persisted entities and add/remove buttons. By clicking the add button, a new select field with the same options appears below the first, which adds a new entry in the M2M relation. By clicking remove the field disappears and the entry should be removed.
The model:
Two entities: User & Manager. A User has exactly one "special" Manager and unlimited normal Managers.
Managers manage unlimited users.To model this I have created two relationships for which the user is the "owner" (not sure how to translate this)
ManyToOne specialManager
ManyToMany normalManagers
I haven't created a many to many relationship with attribute "special" because the requirement is exactly one special manager and I wasn't sure if Symfony/Doctrine would cause problems down the line.
What I have:
I can display a multiple select field with the existing entities using Entity field type, as per the documentation. Functionally this is what I need, visually it is not.
I can also use the Collection field type to display a single text field, and add or remove more with JS, as per the documentation. Visually this is what I need, but The text fields (entity attribute) need to be replaced by choice field.
The question:
Before I continue digging, is there a simple way to achieve this list of select tags?
For anyone else who may eventually need a dynamic list of select fields:
I initially solved this issue by detaching the field(s) in event listeners, and handling the display/submission manually in the controller.
However I wasn't satisfied with this clunky solution and when I encountered the same need I used a second solution: creating an intermediary entity xxxChoice (in this case ManagerChoice) which is Mto1 inversed related to User and Mto1 related to Manager. Then by creating a ManagerChoiceType form with "Manager" entity field type I was able to easily display my collection of dropdown select lists.

Entity Framework - Entity not added to design surface

I attempted to update my edmx file by selecting a table. The tool spit out a info message that said the table did not have a primary key.
The entity did not get added to the design surface but it did get added to the .edmx file. In addition, using the model browser I see an Entities.Store and an Entities. My table got added to Entities.Store, but not to Entities.
I cannot access the table that was "added" in the code.
What do I do?
Steps to reproduce:
Create a SQL table with two columns that are both defined as foreign keys to other tables. Make sure the tables that the FKs point to already exist in the model on the design surface.
Right click and choose Update Model from Database...
Next. Under the Add tab, mark the new table under Tables
Click Finish.
An association will be created and it will be selected on the design surface, but it won't start with FK_, it will just be the name of your table. Go to the Model Browser and look under Entity Types. The table will not be there. Look under Associations and you will see your table name there as an association, but it will look out of place (because of the name).
Entity Framework was too smart for me. It created an association instead of an entity. Odd, but it works for how I need to use it.

Create One-to-One relationship based on PK of both tables

I'm really new to Entity Framework (currently using EF5) and vs2012 and am having difficulty trying to figure something out.
I have an .edmx that was generated from my database. It has two tables in it: Item and 3rdPartyItem. In short, the Item table is the main table for all the company items while the 3rdPartyItem table is a table that is used to hold additional attributes for items. This 3rdPartyItem table was created by an outside company and is used with their software for the company, so I can't mess with either table. What I'm trying to do is show a list of Items in a grid but I need to show a combination of all the fields for both tables. In vs2012, if I create a relationship and make it 'zero-to-one' (because for each record in the Item table, there doesn't necessarily have to be one in the 3rdPartyItem table), vs complains about not being mapped correctly. When I set the mapping, it then complains that there's multiple relationships. I did some research and found that you can't create a relationship with 2 primary keys, so I was thinking that was the problem. But how can I change the .edmx so that in code, I can access Items and 3rdPartyItem like so:
var items = dbContext.Items;
items.3rdPartyItem.SomeField <--field from 3rdPartyItem table.
not too sure if it's even possible, but it would be very, very helpful if so. Any ideas?
What you're looking for is table-per-type (TPT) mapping inheritance. You can view an MSDN walkthrough here (although you'd want your base type to be instantiable):
http://msdn.microsoft.com/en-us/data/jj618293.aspx

Entity Framework STEs and many-To-many associations

I'm fairly new to EF and STE's, but I've stumbled on a painful point recently, and I'm wondering how others are dealing with it...
For example, suppose I have two STE's: Employee and Project. It's a many-to-many relationship. Each entity has a navigation property to the other (i.e. Employee.Projects and Project.Employees).
In my UI, a user can create/edit an Employee and associate it with multiple Projects. When the user is ready to commit, a list of Employees is passed to the server to save. However, if an Employee is not added to the "save list" (i.e. it was discarded), but an association was made to one or more Projects, the ApplyChanges extension method is able to "resurrect" the Employee object because it was "connected" to the object graph via the association to a Project.
My "save" code looks something like this:
public void UpdateEmployees(IEnumerable<Entities.Employee> employees)
{
using (var context = new EmployeeModelContainer(_connectionString))
{
foreach (var employee in employees)
{
context.Employees.ApplyChanges(employee);
}
context.SaveChanges();
}
}
I've been able to avoid this issue to now on other object graphs by using FKs to manipulate associations as described here: http://blogs.msdn.com/b/diego/archive/2010/10/06/self-tracking-entities-applychanges-and-duplicate-entities.aspx
How does one handle this when a many-to-many association and navigation properties are involved?
Thanks.
While this answer's a year late, perhaps it will be of some help to you (or at least someone else)
The simple answer is this: do not allow Entity Framework to infer m:m relationships. Unfortunately, I'm not aware of a way of preventing this, only how to deal with it after the fact.
By default, if I have a schema like this:
Employee EmployeeProject Project
----------- --------------- ----------
EmployeeId ---> EmployeeId |--> ProjectId
Name ProjectId ----- Name
... ...
Entity Framework will see that my EmployeeProject table is a simple association table with no additional information (for example, I might add a Date field to indicate when they joined a project). In such cases, it maps the relationship over an association rather than an entity. This makes for pretty code, as it helps to mitigate the oft-referenced impedence mismatch between a RDBMS and object-oriented development. After all, if I were just modeling these as objects, I'd code it the same way, right?
As you've seen, however, this can cause problems (even without using STE's, which cause even MORE problems with m:m relationships). So, what's a dev to do?
(The following assumes a DATABASE FIRST approach. Anything else and you're on your own)
You have two choices:
Add another column to your association table so that EF thinks it has more meaning and can't map it to an association. This is, of course, bad design, as you presumably don't need that column (otherwise you'd already have it) and you're only adding it because of the particular peculiarities of the ORM you've chosen. So don't.
After your context has been generated, map the association table yourself to an entity that you create by hand. To do that, follow the following steps:
Select the association in the designer and delete it. The designer will inform you that the table in question is no longer mapped and will ask you if you want to remove it from the model. Answer NO
Create a new entity (don't have it create a key property) and map it to your association table in the Mapping Details window
Right-click on your new entity and add an association
Correct the entity and multiplicity values (left side should have your association entity with a multiplicity of *, right should have the other entity with a multiplicity of 1)
Check the option that says "Add foreign key properties to the Entity"
Repeat for the other entity in the association
Fix the property names on the association entity (if desired...not strictly necessary but they're almost certainly wrong) and map them to the appropriate columns in the Mapping Details window
Select all of the scalar properties on your association entity and set them as EntityKey=True in the Properties window
Done!

Entity framework - "Problem in mapping fragments"-error. Help me understand the explanations of this error

Error 3007: Problem in Mapping Fragments starting at lines 186, 205: Non-Primary-Key column(s) [WheelID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified.
I found several places on the web describing this error, but I simply don't understand them. (confused smiley goes here)
One
Two
Three
Four
There is something pretty fundamental here, I must be missing. Can you explain it, so that I understand it? Maybe using my real life example below?
Foreign key 1:N Wheels.Id -> Slices.WheelId
I add them to entity framework, and WheelId is not visible in the Slices-entity.
Doing some workaround (deleting the relationship from the db before adding tables to EF - then re-creating it and updating EF) I managed to get the WheelId to stay in Slices, but then I get the error mentioned at the top.
Since Slices.WheelId is an FK, you cannot expose it in your client model, period. There are ways to get the value, though.
var wheelId = someSlice.Wheels.ID;
Update In EF 4 you can do this by using FK Associations instead of independent associations.
Try to remove foreign property column from Entity set using entity model design it will solve your problem
For example
We have two tables one is customer and other one is order, using entity model design we added association between customers and orders when we do this Ado.net entity framework i will add navigation properties to both below tables.
Like
Customer.Orders - Here order is list
Order.Customer
One - Many relation.
So we need to remove property from with name CustomerId[Foreign key column] from Order entity set.
For reference:
http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/2823634f-9dd1-4547-93b5-17bb8a882ac2/
I was able to overcome this problem by the following steps:
right click the designer window
Select 'update model from database'
Select Add AND make sure that the 'Include foreign key columns in the model' checkbox is selected.
click on Finish...
I had set foreign keys up in the database but framework still wasn't pulling them in correctly. So I tried to add the association myself. 
However, when I did this I would get a mapping error. It took me A WHILE but I figured out. What I did was set up the association using the entity toolbox association tool and then you have to double click on the association (1 to many) line and set the primary and foreign key there. Hopefully, this to help others who might have the same problem. I couldn't find the answer anywhere.
I had this problem for quite a different reason, and the message was slightly different; it didn't say "data inconsistency is possible because the corresponding conceptual side properties can be independently modified."
I have a table involved in my model with a binary column where I store image data. I only want this data returned when I need it (performance is a feature), so I split the table using a method similar to this. Later on, I added a property to that table, then updated the model from the database. The wizard added the property to both entity types that refer to the table with the added property. I had to delete it from one of them to solve the error.
I've had this happen because Entity Framework Update wizard mismapped some keys (or did not update?). As a result, some columns were mistakenly labeled as keys, while actual key columns were treated as plain columns.
The solution was to manually open EDMX file, find the entities, and update the keys.
Couldn't get any of the answer to work with EF6. The problem seems to be the framework doesn't import the foreign keys correctly as Associations. My solution was removing foreign keys from the tables, and then manually adding the associations using Entity Framework model, using the following steps: Entity Framework - Add Navigation Property Manually
For LinQ to Entities queries in EF1, my workaround for not having access to the foreign key as a property is with the following code, which does not produce a join query to the associated table:
dbContext.Table1s.FirstOrDefault(c => (int?)c.Table2.Id == null)
i.e, the generated SQL is:
...WHERE ([Extent1].[Table2Id] IS NULL)...
Solution is to allow deleting Rule = Cascade on Sql association.
Same thing as to be done on .edmx model, adding element to
association:
<Association Name="FK_Wheels_Slices">
<End Role="Wheels" Type= "your tipe here" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
</Association>
I had a table already mapped in EF. I added two more tables which had foreign keys in the previously added table. I then got the 3007 error.
To fix the error I deleted all three tables from the EDMX file, and then re-added them all at once together (via "Update Model from Database..."), instead of in stages.
I checked my Error List window and noticed I had errors in the model. Fixed them and all is well
in my case I solved this error by tick (include foreign key columns in the model)
- update Model from database
- tick (include foreign key columns in the model)
- finish