How can I Add data to a many-to-many relationship using Entity Framework?
I have got a problem when I try to add one article with its related categories (see diagram), but the thing is that the categories already exist in the Categories Table, i don't need to create them again. When I use EF Method: _ctx.Articles.Add(newArticle), It generates insert sentences to categories table and duplicate my rows. Basically, I only need to add data to Article table and the reference table CategoryArticles. Add method, add rows to Article table (ok) plus Category table (wrong step) plus CategoryArticles table (ok).Any Idea How can I avoid to add these rows in my category table again.? Appreciate any help.
EDIT: I AM USING AUTOMAPER FOR FILLING AN ARRAY OF CATEGORIES... I DO NOT IF MAYBE DOING IT ON THAT WAY I AM CREATING NEW OBJECTS. IT IS THE CODE:
List<CategoriesViewModel> categoriesViewModel = article.CategoriesViewModel.Where(c => c.IsSelected).ToList();
List<Category> selectedCategories = Mapper.Map<List<CategoriesViewModel>, List<Category>>(categoriesViewModel);
newArticle.Categories = selectedCategories;
_ctx.Articles.Add(newArticle)
This is the relational model
Thanks to #Robert McKee, the way to solve the problem is to fetch the categories directly from the database, that way the entity framework automatically recognise these categories when the main entity is being saved, avoiding duplicate them.
Many to Many relationships hide the cross reference table in EF. The relationship model shouldn't show the CategoryArticles table at all. The Articles table should have a "Categories" navigation property. Just add a category to it, and save.
Related
I ask only a Model not codes or how can i add them to list or what is right codes. I learned how can i add attributes to entities and fetch them. I need only how can I do Main list which will contain my all entities and attributes. When i want to show me the Favorite players in all entities it should show them all for me..
I created a datamodel for my data based project. I should explain my project.
I want to create a League table view which is contain my all teams and user can add teams in this leauge tableview in add teams viewcontroller.
I created two Entities first entity name is Teams, second Entity name is FavoritePlayer.
My League table view should show all user added Teams in cell text and Favorite players in cell detail text How can i do that with CoreData. I want to learn CoreData so and don't want to do this with Arrays or Dicts.
Should I create another Entity which name is Leagues ? if Yes, How can i do this without attributes ?
or Should I use Parent Entity option.
Actually what is the right way for create a datamodel ?
Thank you !
--------------------- UPDATED QUESTION ------------------------
First of all Thank you very much stevesliva.
I have to explain my project to you for answer me easily..
I want to make a easy user entry database. My project will contain ;
1- MainList Entity which is the main entity and first scene in my app.
MainList Entity doesn't have any attributes. It will show all Entities properties. It's TableViewController and 1 bar button to go addList.
AddList is a tableview controller. It has 2 static Cell titles are Bills and Bank Loans.There are 2 cell segue for go to the these items AddViewControllers.
2-I created BankLoan and Bill Entity. They have attributes.String and Number.
Bankloan has bankName and loanTotal
Bill has billName and billTotal
They have AddViewControllers to add these datas to their Entities.
CoreData Model;
MainList have two to many ordered relationship with bankLoan and Bill
bankloan and bill 1 To One relationship with MainList entity and of course inverse. And I created 2 Custom NSManagedObject class from Xcode Editor menu.
MainList custom class have 2 NSOrderedSet.
#property (nonatomic, retain) NSOrderedSet *bills;
#property (nonatomic, retain) NSOrderedSet *bankLoans;
Now there are my problems ;
1-I can't Fetch managedObjectContext all Entity items. I can Fetch only empty mainList Entity. and I cant create a FetchResultsController because fetchResultsController require a sortDescriptor. I cant create sort Descriptor either because i don't have any attributes in MainList. That is the first problem.
2- If I add all properties to NSOrderedSet how can I fetch datas with SQLLite codes.exp: LIKE,[c] >== or <== codes.I cant create Fetchresultscontroller without attributes. when I want to show only bills BeginsWith "something". I cant do..
What is the best way to create this project with Core data?
What will you do in this situation ?
Thank your for your interest and all answers. You are very helpful for me.
Create a team entity.
Create a player entity.
If you want a league entity, it would have a to-many relationship to team. And a to-one from team to league. League would not be a "parent" of team, because team doesn't subclass league. You should create a league entity if you want to track leagues in core data. If you don't want to leagues to have any attributes, then they can just have a relationship to teams, but then you wouldn't be saving any other information, like the leagues name, to the persistent store.
Create a to-many relationship from team to player.
Create a relationship from player to team.
Create attributes for the information you want associated with each entity.
That is the way to create the data model.
Then, create a subclass of UITableViewController. Have it be the delegate and datasource for your UITableView instance. Have it implement the functions you need, which fetch from and modify the managed object context.
Alternatively, you could have the UITableViewController subclass use a singleton teamManager or playerManager or whatever. Here is a blog post about singleton "managers:"
http://www.galloway.me.uk/tutorials/singleton-classes/
I believe that answers all of your questions.
Oh. Except for the "why don't people want to answer me."
It is not clear what your problem is. It's not clear whether you are only asking about what data model would be best, and if you are, it's not clear what you don't understand. We need some known unknowns.
Stack overflow is good for answering specific questions. It is not a place for on demand tutorials. There are likely dozens of core-data-to-tableview tutorials you could find. You are supposed to read those first.
Background Info
So I am using Breezejs and Knockout with EF5 and the Breeze MVC api controller on the backend. One of my tables in my data base is an association table, 3 columns - an id and two foreign keys(we'll call them fkey1 and fkey2 with table1 and table2). In my application, I need to add a record to this association table. Breeze knows about the relationships that this table has.
Situation
Breeze js makes a new record for me, then I find out the records I need to associate with it. Do I need to add in the id of the table1 entity into the fkey1 observable and the table2 entity id into the fkey2 observable AND add the whole entities into their respective relationship properties AND add push this new entity object into the table1 and table2 entities association property? Or does adding the id's into the new object automatically add those objects into the relationship properties (maybe those objects are subscribed to the fkey1 and fkey2 properties? - this is what I'm guessing happens in the background of breeze, a shot in the dark though I have no idea).
Creating new entities with Breeze is super easy and I love it, but I'm a little confused when it comes to creating new entities that have a lot of relationships.
Let me if you need a better description of my situation, it's kind of a tough thing to explain. Thanks!
Providing that you set the "foreign key" properties appropriately when creating and attaching entities, Breeze will automatically update all of the associated relationships, i.e. navigation properties on this and any related entities. You should never need to manually perform any fixup.
Similarly, if you do the reverse and assign an entity to a scalar navigation property then Breeze will automatically update the foreign key(s). For a collection navigation property, if you push a value into the collection then Breeze will automatically update the foreign key of the entity being pushed.
Hope this helps, but maybe I'm missing the question...
I currently have an EF class that is backed by a database view (joining multiple tables). To make it updatable, I need to change the class to be backed by a database table. I am using Entity Framework 4.1 Code First and can't figure out how to set up those relationships?
To simplify, I currently have a Categories class that returns the Category Name (Categories table) and Category Type Name (CategoryTypes table). These are both in the database view that I currently use. I want to change to a ViewModel that brings back both of these fields directly from their tables and joins properly, that way when a user updates a Category Name, EF should be able to properly handle the update (since it will be updating the table instead of the view). Any tips on how to do this?
Table is a table - it is a single database object. If you want to remove your view and replace it with a table you need to delete your current tables (Categories and CategoryTypes) and create a single table which will contain denormalized data. That is pretty bad solution and it will cause you problems in the whole application.
Just to simplify description: It is not possible to replace your view constructed by joins among several tables with a table and it is not possible to make your view updatable.
You are doing it wrong because you are obviously mapping view models directly to your database. Map Catagories and CategoryTypes to entities load Category with its CategoryType and flatten them to your view model in your application logic (or load the view model through projection). Once user updates your view model decompose it back to separate entities and save them.
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.
I have asp.net membership and I use the built in Create user method since it is convenient now after this depending on the user I want to add 2 more fields to the aspnet_UserTable.
In my aspnet_user Table I have like this
// All Standard Fields that come with this table
ClubID<nullable)
ClubName <nullable)
I have a table that relates this
Club Table
ClubID<PK>
ClubName
So this relationship forms that one club can have many users. But one user can only have 1 club.
So now I been trying to figure out how to add the ClubID to the aspnet Usertable since it does not show up in the Entity Framework Diagram since it does not show FK.
// Note in this case I am just using EF made to create but in reality I will use the Membership.Create.
aspnet_Users test = aspnet_Users.Createaspnet_Users(Guid.NewGuid(), Guid.NewGuid(), "myTest5", "mytest5", false, DateTime.Now);
test.Club = Club.CreateClub("One224", "Two224");
test.ClubName = "go";
MyEntities.AddToaspnet_Users(test);
MyrEntities.SaveChanges();
So what I have works but it just makes no sense and I hope there is a better way. Like I try to create the club and then stick it in the test.club.
This add's the ClubID primary key but does not add the clubName.
So then I have to add the club name separately. Like why? Is there not a better way?
I also prefer linq method syntax so if it is needed and you know this syntax can you please write it in that.
I would recommend a few things.
One: Strongly consider not adding columns to the aspnet_* tables. If you ever want to change your authentication method down the road you'll be stuck lugging those tables around with you even though you won't need them anymore. Also, there may be a new, better version of the membership provider one day that you won't be able to upgrade because you have customized the membership schema.
Two: Instead, why not create a new table called User (or something of your liking) that has your own primary key but links back to the ASP.NET Membership unique key (the guid).
Your table might look like
User
UserId (PK)
AuthenticationUserId (FK back to aspnet_User table)
ClubId (FK back to your club table)
Three: I don't understand why you've repeated ClubName both in your user table and in your Club table. You really only need to define the ClubName once, right? Keep your Club table how it is but remove the ClubName column from the user table.
Your code above for associating the club with the user is correct and works because that's how the Entity Framework works. You're associating entities with each other and are abstracted from some of the relational aspects of your data schema. It's a little strange to get used to it first but it does work.