Entity Framework 4: Self referencing entities, parent/child - entity-framework-4

we are using a model first design.
When I create a self referencing parent child association on an entity the designer always marks one end "many", which would be the "children" and is ok like that.
But the designer makes the other end "1 (One)", which is not ok since a parent is not required. If I change it to "0..1 (Zero or One)" the designer changes the other end from "* Many" to "0..1 (Zero or One)". So both ends are "0..1 (Zero or One)".
This is driving me crazy :(
What am I doing wrong?

Is the 'ParentKey' column marked as nullable (Both in DB & EDMX)? Could prevent the relationship type you are after from being set up.

Related

Do i need a core data migration when i add a new model to my .xcdatamodeld file

i have a an .xcdatamodeld which already has 2 entities, i have added another entity into this file(am not sure whether this is the right way to add a new entity), anyways my question is, do i need to implement any kind of migrations to take care of users who already have the app installed on their devices.
Please note, i have not modified any columns or schema on already existing entities.
cheers.
You don't need to do migration if you just only adding new entity, assuming that it doesn't have relationship with the other. According to raywenderlich.com, you have to do migration for the following scenario:
Deleting entities, attributes or relationships.
Renaming entities, attributes or relationships using the renamingIdentifier.
Adding a new, optional attribute.
Adding a new, required attribute with a default value.
Changing an optional attribute to non-optional and specifying a default value.
Changing a non-optional attribute to optional.
Changing the entity hierarchy.
Adding a new parent entity and moving attributes up or down the hierarchy.
Changing a relationship from to-one to to-many.
Changing a relationship from non-ordered to-many to ordered to-many (and vice versa).

Prevent EF6 from generate navigation properties

I've recently started to use EF6 and i'm building a couple of T4 templates to generate some code automatically (on VS2012).
I'm generating my model from the database and this process creates all the associations automatically based on the DB ForeignKeys. And generates too a "Navigation Property" for that field in Associations/FK.
I want to get a "Flat Version" of my entities without navigation properties. Just a class with properties corresponding to table columns.
Is there any way to "Generate Model from Database" and get this? i've tried to update model with the option "Include foreign key columns in the Model" unchecked, but the associations and nav props are still being generated.
thanks in advance
You must edit the t4 template that builds the model classes to get this done.
In your project you'll find two .tt files, something like ModelName.Context.tt and ModelName.tt. The latter is the one that builds the model classes.
Look for these two lines
this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
(probably around line 50)
and
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
(probably around line 100)
and erase these lines.
Now when you save the template, your classes will be re-generated without navigation properties.
SOLUTION FOUND
As i was reading the conceptual model, i was getting innaccurated information about the table structure, because the conceptual model on the edmx, because when we have foreign keys, associations are created and Nav props instead of regular property (on the fields withing the FK).
The solution i Found is use the store model instead of Conceptual model
Getting the Conceptual Model "Wrong way"
MetadataLoader loader = new MetadataLoader(this);
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
Getting the Store Model "GOOD way"
MetadataLoader loader = new MetadataLoader(this);
StoreItemCollection ItemCollection = null;
loader.TryCreateStoreItemCollection(inputFile, out ItemCollection);

Replace entities in to-many relationship in Core Data

When I retrieve an entity from the one side of a one-to many relationship, I create a mutable array from the set that is the collection of entities from the relationship. I manipulate, edit or otherwise change those entities, possibly delete existing or add new.
When through with the changes I simply use the array to create a new set then replace the original set with that which I created like so:
self.myOneSideEntity.theManySideEntitiesRelationship = [NSSet setWithArray:myNewArrayOfEntities];
It occurred to me that replacing the set may not be deleting the old members. What happened to them? Is this the proper way to edit the collection of related objects? Am I leaving any kind of orphans or going against best practices with this technique?
My relationship is set up with an inverse, cascade delete on the one side, nullify on the many side and the inverse relationship is not optional.
I've spent some days to understand similar behavior in my application.
Relation's "Delete Rule" works only when the object that contains relation is deleted itself. If you simply replace one set of objects with another (as you do) - nothing happens. Child objects that were in old set will simply have inverse relations set to nil. So if that relation (from child side) is not optional, you will get CoreData error when saving context.
For now I didn't find any way to manage this, except manual deletion of old objects.
For me the issue was with getting objects which were wired with current object. (groupObject.docs)
It was solved when I add context by which I get this data.
I'm using MagicalRecord:
[GroupObject MR_findAllInContext:[NSManagedObjectContext MR_defaultContext]]
instead of
[GroupObject MR_findAll]

Entity Framework 4.0 2 many-to-many with same entities

I have 2 entities (say People and Books) that have two many-to-many relationships. I have created two different linking tables - e.g. the linking tables are called BooksCheckedOutByPeople and BooksOnHoldByPeople.
EF 4.0 correctly makes two relationships. It calls them something like PeopleBooks and PeopleBooks1.
When I am making Linq queries, how do I tell Linq to use a specific one of these relationships? Is there any way in Linq to specify one relationship instead of the other?
Say I'm creating a query against People and I want to get the Books for BooksCheckedOutByPeople and thus I need to use the relationship PeopleBooks.
Thanks.
You should be able to rename "PeopleBooks" and "PeopleBooks1" to more informative property names by editing the model EF generates for you. Something like "BooksOnHold" and "BooksCheckedOut".
At that point, when writing your LINQ queries, just reference the right navigation properties (as they're called). LINQ uses whichever properties you specify, and the Entity Framework should generate a unique navigation property for each collection.
Edit
I just fired up VS2010 to copy your model and poke around a bit.
I see that EF4 did indeed generate two Navigation Properties foor Book and Person, called People and People1, and Books and Books1 (respectively).
If you select any of these Navigation Properties in the Model Browser and look at the Properties pane, you should be able to see which table is correlated to that association and rename the property appropriately. Here's a screenshot from my PC:
You can see that I've selected the "People" nav property for the "Book" entity. The association in this case is determined by BooksCheckedOutByPeople, so I can rename the property to "PeopleCheckingOut", or something more useful than "People". When I'm using LINQ-to-Entities later, I then reference the "PeopleCheckingOut" property to query that collection on any specific Book.

Simple one to many relation (association) fails in EF designer

I tried setting up a simple one-to-many relation in Entity Frameworks designer.
The tables are Category (1) and Transaction (N). Here's what I did:
Add "association"
End1 = Category, multiplicity 1, navigation property=Transaction
End2 = Transaction, multiplicity Many, navigation property = Category
Building it gave me the error "No mapping specified". Ok, makes sense. So I added this mapping:
Category
Category.CategoryID = Transaction.CategoryID
But the mapping designer also automatically adds a mapping for the Transaction table, which I cannot figure out how to delete or how to setup:
Transaction
Transaction.TransactionID = ???
Leaving it empty seems most valid, but that gives me: Error 3024 "Must specify mapping for all key properties (TransactionID)"
And trying to set it to a fake int property just hoping it's a compiler bug. But that gives me errors 3002 and 3003.
I dont get what to do. Isnt Associations meant to be used this way?
I suggest creating (or importing from the database) an entity for Catagory and an entity for Transaction. Add scalar properties to each as needed. Next, right-click on your entity, click Table Mapping, and map your entity properties to the table fields. For example, for the Category entity, map CategoryID field to a CategoryID property. Do the same for the other entity. THEN create the association.
Note that associations linked by exposed foreign keys do not have any mappings.
BTW, you'll probably want to add navigation properties as well.

Resources