ADO.NET recurring results from relationships - sql

I'm working on a project in ASP.NET MVC 5, with ADO.NET EF to generate data from the SQL server. I have several one-to-many relationships in the database. When I fetch data and project it to a local variable, e.g. var query = model.listFromDbChildTable.ToList(); where model.listFromDbChildTable is just entities loaded from the db. This is the lowest table in the relationship hierarchy.
So the thing is, and I am not sure why, every time I go to "locals" in VS, in debug mode, I can go deeper and deeper into my relations, for example, I am looking at a child table (department), and when I go to this child in locals, I see child has a relation with parent (above it), s I go to parent table, (I believe this is normal,) but when I'm at parent (table), again I can go to child table from there, and I am not going up one step back in the hierarchy, but so to say deeper, like a stair down all the time. So I go again to child, and child can go to parent again, every time with the same element. And I can redo this process many times?
So what is going on? Are my relations wrong or is this some normal procedure with locals in VS?

The following image shows two tables that participate in one-to-many relationship. The Course table is the dependent table because it contains the DepartmentID column that links it to the Department table.
Basically any link between two entities can be explored(Table in SQL ,class in EF)
In SQL you refer just a column in child table as key whereas in entity a property is create which has type of a class .
Like in below example, Course will have property name "Department" of type "Department" class as it depends on it (also a DepartmentId property).
you can read more in detail here on msdn..and Don't worry moving from SQL to Entity framework does give you small suprises :) .Hope it helps.
Parent Child Entity MSDN

Related

Parent & Child FK'ing to same table

What is best practise when a parent & child table both FK to the same table?
Parent > Child(ren)
CommonAttributes: Sex, Age, Height, Weight
Is it better to directly reference the common table:
CommonAttributes > Parent(s) > Child(ren)
&
CommonAttributes > Child(ren)
Or use a reference table:
RefTable: CommonAttributes_Id, Parent_Id(null), Child_Id(null)
I think the first method works OK (with regards to EF) but it is a bit of a circular reference. Is it better to use a reference table to define the constraints?
There are several approaches to this and the one you need depends on your business needs.
First, can a child record have more than one parent? For instance you might be modelling an organizational structure where an employee can have two supervisors. If this is true, then you have a one to many relationship and need a separate table for this model to work.
If you are guaranteed to have only one parent per child (but each parent might have a parent (building a hierarchy), then you can model this is one table. The table structure would include the Primary key, say UserID and then a nullable column for the parent such as ParentUserID. Then you can create the foreign key to the field in the same table.
ALTER TABLE dbo.Mytable ADD CONSTRAINT FK_Mytable _UserPArent FOREIGN KEY (ParentUserD) REFERENCESdbo.Mytable (UserID)
If you want to build a hierarchy in a query, you then use a recursive CTE to get it. See example here:
https://msdn.microsoft.com/en-us/library/ms186243.aspx
Another time you might want to build a separate table for the child parent relationship is if only a small portion of teh records in the main table would have parent child relationships. For instance suppose you had a people table that stored, sales reps and customers. Only sales reps would have a parent child relationship. So you would want a separate SalesRepHierarchy table to store it which woudl make querying more straightforward.
While in general you woudl want to create hierarchies in a recursive CTE, there are special cases when it might be faster to pre calculate the hierarchies. This is true if the hierarchy is frequently queried, the CTE performance is slow and you have control over how the hierarchy is built (preferably through an import of data only) and if it changes fairly rarely (you would not want to be rebuilding the hierarchy every minute, but a once a day import can be accommodated. This can greatly speed up and simply querying for the whole hierarchy, but is not recommended if the parent child relationships are created and changed constantly through the application.

Use Foreign Key on SQL View in Entity Framework

I'm relatively new to Entity Framework.
I created a database with two tables: Accounts and Assignments.
Accounts has an AccountId primary key which is used as a foreign key in the Properties table. I really like that the Entity Framework automatically picks up the foreign key relationship and allows me to access rows in Assignments as a property of each row from Accounts.
I went ahead and created a new View object that returns all the columns from Accounts along with some other information. However, when I get the data from the View in SQL using the Entity Framework, it is no longer automagically referencing the associated rows in the Assignments table.
How can I get the desired behavior using Views with Entity Framework
This can work in EF, but the EF designer can't infer your FK out of the view, since the DB doesn't tell it where the FKs on view columns are (since they're naturally on the underlying tables, not the view itself).
You'll need to manually edit your EDMX, either via the designer or in XML, to get these properties.
The solution that worked for me was to include the appropriate data in the view so I didn't need to use the FK.
For example, include the PK's for the Assignment table in the view by adding the appropriate SQL to the view.
That way I could join to the view in LINQ without needing to refer to a generated property in the EDMX.

iOS CoreData - Rebuild relationships

I'm wondering if it's possible to "rebuild" relationships in Core Data.
Basically, I messed up when creating my entities, getting data from a SQL server i filled my entities as tables (one table by one table) and it seems now that the relationships are not working.
Let's take an example :
I've set up my model with my two entities (department and employee), with a relation one-to-many "myRelationWithDepartment" (one department many employees), and generated the managed object subclasses accordingly.
I got table department and table employees from my SQL server and inserted all employees in my entity employee and only then (because i have to retrieve first employees) all departments in my entity department, using Core Data, saving context, etc. Everything is fine, just the relationship is not working.
Now I'm able to make a fetch request upon a department or an employee, it works fine. But if I retrieve an employee and do this :
[[anEmployee myRelationWithDepartment] departmentName];
it's returning nil, no compilation warnings or errors, it just seems that no department is linked to an employee.
So I assume that the relations are not working.
I've included in the model the "id"s I had in my SQL tables, so I'm able to link them manually (but i have multiple entities actually).
I've gone through the Core-Data guide and found this :
[aDepartment.employees addObject:newEmployee]; // do not do this!
then KVO change notifications are not emitted and the inverse relationship is not updated correctly.
Recall that the dot simply invokes the accessor method, so for the same reasons:
[[aDepartment employees] addObject:newEmployee]; // do not do this, either!
That's why I assume relationships are badly shaped. Is there a way to rebuild the relationships afterwards (since i share some id's in the model between entities)?
I dig up more in Apple's documentation and relationship has to be filled manually :
To create the relationship "link" :
anEmployee.myRelationWithDepartment = departmentObject;
Alternatively, you can use:
[department addEmployeeObject:anEmployee];
Then when fetching objects you can access properties of related entities.
The problem is that Core-Data is "sold" as everything is doing quite by itself and in reality it's much deeper as it seems at first glance.

Fluent Nhibernate and Dynamic Table Name

I've got a parent and child object. Depending on a value in the parent object changes the table for the child object. So for example if the parent object had a reference "01" then it will look in the following table "Child01" whereas if the reference was "02" then it would look in the table "Child02". All the child tables are the same as in number of columns/names/etc.
My question is that how can I tell Fluent Nhibernate or nhibernate which table to look at as each parent object is unique and can reference a number of different child tables?
I've looked at the IClassConvention in Fluent but this seems to only be called when the session is created rather than each time an object is created.
I found only two methods to do this.
Close and recreate the nhibernate session every time another dynamic table needs to be looked at. On creating the session use IClassConvention to dynamically calculate the name based on user data. I found this very intensive as its a large database and a costly operation to create the session every time.
Use POCO object for these tables with custom data access.
As statichippo stated I could use a basechild object and have multiple child object. Due to the database size and the number of dynamic table this wasn't really a valid option.
Neither of my two solutions I was particularly happy with but the POCO's seemed the best way for my problem.
NHibernate is intended to be an object relational mappers. It sounds like you're doing more of a scripting style and hoping to map your data instead of working in an OOP manner.
It sounds like you have the makings of an class hierarchy though. What it sounds like you're trying to create in your code (and then map accordingly) is a hierarchy of different kinds of children:
BaseChild
--> SmartChild
--> DumbChild
Each child is either smart or dumb, but since they all have a FirstName, LastName, Age, etc, they all are instances of the BaseChild class which defines these. The only differences might be that the SmartChild has an IQ and the DumbChild has a FavoriteFootballTeam (this is just an example, no offense to anyone of course ;).
NHibernate will let you map this sort of relationship in many ways. There could be 1 table that encompasses all classes or (what it sounds like you want in your case), one table per class.
Did I understand the issue/what you're looking for?

Association end is not mapped in ADO entity framework

I am just starting out with ADO.net Entity Framework I have mapped two tables together and receive the following error:
Error 1 Error 11010: Association End 'OperatorAccess' is not mapped. E:\Visual Studio\projects\Brandi II\Brandi II\Hospitals.edmx 390 11 Brandi II
Not sure what it is I am doing wrong.
I believe I can add some more clarity to the issue (learning as I go):
When I look at the Mapping details and look at the association, the column for operatoraccess table (from above) is blank and the drop down only includes field from the linked table.
The Entity Framework designer is terrible - I've had the same problem many times (and your problem too, Craig):
This happens when you have a many-to-one association which is improperly setup. They could very easily fix the designer to make this process simple; but instead, we have to put up with this crap.
To fix:
Click on the association, and go to the mapping details view.
Under association, click on Maps to <tablename>. Choose the table(s) which make up the many side of the relationship (ie. the table(s) which make up the *-side of the association in the designer)
Under Column, choose the table-columns which map to each entity-side Property. You get this error when one of those entries are blank.
I had the exact same problem and this is what I did to fix it.
Make sure you have an Entity Key set in your designer on the tables your making an association with. Also check that StoreGeneratedPattern is set to Identity for that Entity Key.
There's not a lot of information in your question, but, generally speaking, this means that there is an incompletely defined association. It could be that you have tried to map one table with a foreign key to another table, but have not mapped that other table. You can also get this error when you try to do table per type inheritance without carefully following the steps for implementing that feature.
Not sure of the answer, but I've just posted a similar question, which may at least help clarify the issue you are experiencing.
Defining an Entity Framework 1:1 association
I had to go back into the database itself and clarify the foreign key relationship
I had this problem in the case where I was creating both many to 0..1 and 0..1 to 0..1 associations. One entity needed associations to multiple tables, and that entity did not have foreign keys defined for those tables.
I had to do the table mappings step that is given in the accepted answer, but note that it wasn't only for many to many associations; it applied to all the types of associations I added for this entity.
In the Mapping Details view, I had to select the entity with the non-foreign key ID columns to the various tables. This is not always the "many" side of the relationship. Only there was I able to map the related entity property to the appropriate property in the original entity. Selecting the "destination" entity would not allow me to select the properties that I needed to, and the error would still exist.
So in short, I had to map using the table related to the entity that had the "non-foreign key" ID fields corresponding to the various entities' (and their tables') primary keys that I needed to associate.
Entity A
various other properties...
Id
ContactId
OrderId
etc.
Contact entity
Id
FirstName
LastName
etc.
In the mapping details, I selected Entity A's table. It then showed both ends of the association. I mapped its Entity A's Id property to its table's actual ID column (they had different names). I then mapped the Contact entity's Id field to the ContactId field on the A entity.
Simply select the many relationship table (*) from the Association>Edit Mapping & select the appropriate relationship