Deleting Entity With Child Relationships
Apr 10, 2010
EF is so frustrating. I can't seem to be able to get my head around what I need to do so I can delete an object. I seem to be able to remove the object but not the related child objects. Can anyone tell me what is the rule of thumb when you want to delete all related child objects of a given object? I've tried loading all related objects like this:
Entry entry = ModelContext.GetObjectByKey(new EntityKey("ModelContainer.EntrySet", "Id", id)) as Entry;
entry.ChildEnteries.Load();
if (entry != null)
{
ModelContext.DeleteObject(entry);
ModelContext.SaveChanges();
}
I get errors related to the relationships: A relationship is being added or deleted from an AssociationSet 'EntryEntry'. With cardinality constraints, a corresponding 'Entry1' must also be added or deleted. Why can't I just load the object using modelcontext.GetObjectByKey and remove it along with its child objects? My other question is can I delete an object using Entity command like so? DELETE e from objectset as e where e.id = 1 I've tried few variations and all of them throw exceptions.
View 1 Replies
Similar Messages:
Feb 4, 2010
I am just getting started with entity framework with asp.net 3.5 using VS 2008
There are two tables, Categories & Subcategories:
Category table: CID, CategoryName Sub Category table: SID, CID, SubCategoryName I would like to get SID, CID, CategoryName, SubCategoryName in the gridview. Just as we write a select statement i.eSelect a.sid, b.cid, b.categoryname, b.subcategoryname from subcategories a inner join categories b on a.cid=b.cid & put the same in a gridview.
I was trying for the whole day & couldnt get atleast one url that would teach how to do it.
View 3 Replies
Oct 27, 2010
I have the following related tables:
Users
Id
Username
Email
Password
UserStatuses
Id
Name
Users_UserStatus
Id
User (FK - Users: Id)
Status (FK - UserStatuses: Id)
StatusDate
As you can see, UserStatuses is a reference table with various statuses. Users_UserStatus is a join table between Users and UserStatuses. Using Entity Framework, how can I do a conditional to check if the latest StatusDate is "Pending"? As of now, I have the following:
[Code]....
View 1 Replies
Jan 19, 2011
I would like to have a short example on how do you actually perform relationships in Entity Framework 4 Code-First CTP 5 ?
Would love an example for these kind of relations :
* one-to-many
* many-to-many
View 1 Replies
Oct 5, 2010
This is my first attempt at updating a database using LINQtoSQL. At least, it's my first if you don't count the tutorials I've followed. Unfortunately, The tutorials that I have found don't offer much more than updating a single table. I'm attempting to update a DB Model that's a bit more complex.
I have a Stream table:
[Code]....
View 1 Replies
Jan 24, 2011
I'm a newbie to this so bear with me. From what I've read online LINQ to Entity should see the relationships without having to specify the joins between multiple tables. I have a relationship that goes across 4 tables Employee, EmployeeDepartmentLink, EmployeeProjectLink, and Project. The idea is an employee can be in multiple departments and work on multiple projects with it being specified which department the employee is in for that project.
This is a C# MVC3 program connecting to a SQL database using VS 2010 Express.
I have no problem with running this query to find employees on a project:
[Code]....
Tring to do the reverse, finding projects that an employee worked on results in an error:
[Code]....
Error message: The specified type member 'EmployeeDepartmentLinks' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. So I have 2 questions,
1) Why would it work in one direction and not the other? I've played around with it for a couple days with the same results.
2) Does it matter that my primary key and foreign keys are not named the same since all the relationships are connected in SQL? Ex: in Employee (EmployeePK)--(EmployeeFK) in EmployeeDepartmentLink Trying different stuff in LINQPad I was able to get the 2nd query to work if I specified all the joins which I thought was not neccesary with LINQ to Entity. I converted an SQL query that I made on the server into a LINQ query below which works.
View 5 Replies
Sep 20, 2010
I have an entity generated from my database that contains one table. When i make changes in the DB i obviously would like these changes to reflected in my model.
My current approach is to delete the item from the designer and then right-click - update model from database. This works for me at the moment. Is there a different approach to refreshing these entity tables ?
View 1 Replies
Aug 19, 2010
I have the next aspx page.
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="newsEditor.aspx.cs" Inherits="ExpertSiteV2.newsEditor" %>[code]....
In some situation i want to delete all the contents of Panel1. I write in the code:
Panel1.Controls.Clear();
But it doesn't work and i get message: Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Page cannot be null. Please ensure that this operation is being performed in
the context of an ASP.NET request.
Source Error:An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace: [InvalidOperationException: Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request.]
System.Web.UI.ScriptManager.get_IPage()
+373832 System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object
sender, EventArgs e) +54
System.Web.UI.Page.OnPreRenderComplete(EventArgs
e) +8698462
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +1029
Blockquote
What's wrong? Or how should i do this properly?
View 2 Replies
Jul 9, 2010
I have 3 tables User, role and UserInRole THe entity frame work made entities for User and Role and I have successfully made a join with the user and role entities using user.add(role); but I can't seem to get it to remove the link (I want to retain the user and role just remove their association).
using (ProviderEntities context = new ProviderEntities())
{
User u = context.User
.Where(n => n.ApplicationName == application)
.Where(n => n.Username == username).First();
Roles r = context.Roles
.Where(n => n.ApplicationName == application)
.Where(n => n.RoleName == roleName)
.First();
r.User.Remove(u);
context.SaveChanges();
}
The oposite worked when I did r.User.Add(u); but it wont let me now remove it after it been created. Driving me mad as I can't see where I have gone wrong.
View 1 Replies
Apr 20, 2010
how can i retrieve the all foreign keys against a single primary key. i mean to say that if a table contain a primary key then it becomes as foreign keys in which tables.
i want to take that nam of that tables and on the base of that tables then i am to delete from all the entries. e.g: if a primary key's column entry deleted then all foreing key entries should also be deleted.
there are 988 tables in a single database. it can't be possible to go for each table to setup foreign key to ON DELETE CASCADE.
.can it have any way to delete against foreign key priority wise? mean to say that parent table contain primary key, child table contain foreign key , now there is another child table which dependent previous child table. then how can i delete all record against it?
i want to do it from programatically. i am using sql server 2005
i have completed this till to that , it retrieves all foreign keys but how to delete now on the base of priority.
[Code]....
View 1 Replies
Mar 10, 2010
i have 2 tables without any cascade deletind. i wont to delete parent object with all child objects. i do like this
//get parent object
return _dataContext.Menu.Include("ChildMenu").Include("ParentMenu").Include("Pictures").FirstOrDefault(m => m.MenuId == id);
//then i loop all child objects
var picList = (List<Picture>)menu.Pictures.ToList();
//foreach (var item in menu.Pictures)
for (int i = 0; i < picList.Count; i++)
{
if (File.Exists(HttpContext.Current.Server.MapPath(picList[i].ImgPath)))
{
File.Delete(HttpContext.Current.Server.MapPath(picList[i].ImgPath));
}
if (File.Exists(HttpContext.Current.Server.MapPath(picList[i].ThumbPath)))
{
File.Delete(HttpContext.Current.Server.MapPath(picList[i].ThumbPath));
}
//**what must i do here?**
//menu.Pictures.Remove(picList[i]);
// DataManager dm = new DataManager();
// dm.Picture.Delete(picList[i].Id);
//menu.Pictures.de
//_dataContext.SaveChanges();
//picList[i] = null;
}
//delete parent object
_dataContext.DeleteObject(_dataContext.Menu.Include("ChildMenu").Include("ParentMenu").Include("Pictures").FirstOrDefault(m => m.MenuId == id););
_dataContext.SaveChanges();
View 1 Replies
Nov 25, 2010
I am having a meltdown over something that seems so simple and yet isn't working. Here's my scenario.
I have an object structure of tEvents, which contains properties of an event like a run of concerts. tEvents in turn contains an entity set of tEventOptions, which include properties like EventDate, Cancelled etc. I would like to query a list of tEvents using properties of the tEventOptions, for example filtering by date.
My pageis using a calendar object to show event dates. So I am trying to find if any tEvents in the List coming back from the database match the date of the day element being rendered in my Calendar control like so (in this snip 'data' is List and results from a db query):
[code]....
Except r, my query result var, is always true no matter what data it receives. I have tried the sub query using other properties of tEventOption and get the same 'true' result each time. I know that the data does not reflect this result so I clearly have a problem with the structure of my query, but for the life of me I cannot find a way to resolve it.
View 1 Replies
Feb 20, 2011
I want to be able to update a model and all its collections of child objects in the same view. I have been referred to these examples: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ .
For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. In the view, the simple properties of the Consultant object is no problem, but the collection I cannot get a textbox to show up for. I tried following the examples in the links above, but it doesn't work. The problem is, in those examples the model is just a list (not an object with a child list property). And also, the model again is an EF model. And for some reason that doesn't seem to work as in those examples.
[Code]....
This stuff with the EditorTemplate works fine in Phil Haack's sample project, which I downloaded to try, but here, with the EF model or whatever the problem is, I don't get any textbox at all. The table in the view is just there as a test, because in the table I do get the rows for WorkExperiences, whether I add an empty WorkExperience object or fill out its properties doesn't matter, the rows show up for each object. But again, no textbox...
View 2 Replies
Sep 27, 2010
I have a repeater which binds a set of data. Within this repeater is a column with various controls for updating, deleting, etc. These are image buttons which fire an onclick event such as "DeleteRecord". All this does is fire a stored procedure, passing in the ID of the record to delete from the CommandArgument of the object.
This works wonderfully... except for one rather huge problem. Once you delete a record, if you refresh the page, the record where the first deleted record used to be gets deleted. For instance... if I have 4 records
1 Record1
2 Record2
3 Record3
4 Record4
and I delete record 2... The page reloads with (which is fine):
1 Record1
3 Record3
4 Record4
...if I then hit refresh...
1 Record1
4 Record4
I assume this is because the erroneously deleted object (record3) is now in the same hierarchical place as the old object used to be and .net therefore doesn't know the difference, the page refreshes and fires the onlick event, grabbing out the command argument of the new object and deletes based on the ID as obtained from the commandargument of the new object. This is obviously a huge problem, if a client did this it would destroy data erroneously and I'm at a loss here. Is there any way to stop this from happening? I'm not sure if there is a better way to go about doing things or not. If there isn't, I need some sort of way to tell the page not to execute the event or to cross reference the ID of the object that is intended for deletion against the object itself...
Code below for convenience...
EDIT Wrapped a LinkButton around it because I have some jquery code in here as well which stops the page execution to wait for user confirmation. Pressing "ok" continues page execution.
<asp:LinkButton ID="oDeleteLink" CssClass="oDeleteIcon" CommandName="Delete" CommandArgument='<%# Eval("iAccountID") %>' runat="server">
<asp:ImageButton ImageUrl="/files/system/icons/trash-steel-16.png" ToolTip="Delete This Account" AlternateText="Delete" ID="oDeleteIcon" runat="server" />
</asp:LinkButton>
protected void oAccounts_ItemCommand(Object Sender, RepeaterCommandEventArgs e) {
if (e.CommandName == "Delete") {
int ID = e.CommandArgument.ToString().Numeric();
db.SPs.SpDeleteAccount(ID).Execute();
UI.Confirm(uiBroadcast, "Account has been deleted", "300px");
BindAccounts();
}
}
View 2 Replies
Jun 30, 2010
I have an EDM, it includes the entities extension and history. My goal is to use history to keep track of all the changes made to extension entity. For example, if extension with ID 223 has its property 'Name_Display' changed - I want the history entity to record this.
I'm using ASP.NET with VB.NET. Where in my code do I put the hook to say, "update the history entity" and what should that hook look like?
View 1 Replies
Aug 5, 2010
What is the best approach to one to many relationships?
This is my scenario:
I have a simple one to many relation:
Customer
CustomerID
Name
tel
CustomerNotes
Id
Note
customerID
I want to have a DETAIL view of customers and CREATE view for CustomerNotes all in the same page.
I create CustomerController and the different views and its respective actions for edit, create, delete, etc.
I also create a CustomerNotesController and the views and actions like before, but I made the views PARTIALS
I put a RENDERPARTIAL for the CustomerNotes create view in the Details view from Customer.
When I run the app, the page is render as expected: It shows the detail info of the customer and bellow the create form for the notes. However, when I click SAVE, nothing happens. I put a breakpoint in the notes controller and never get hit.
I also try with RenderAction and don't work at all.
View 4 Replies
Feb 1, 2010
I'm having a hard time wrapping my head around how to use the Memberships in MVC. I know there is the built in ASPNETDB database which has all the basic tables for users and such. But what if I wanted to add a relationship between one of my custom tables and this built in user table?
If I had a database table that contained blog comments, we'll call it Comment. And each Comment had a userID associated with it could I do something like?
User.Comments.Add(someCommentObj)
View 3 Replies
Jan 8, 2010
Does anyone no of any good resources regarding many-to-many relationships? More specifically on displaying data from many-to-many tables in ASP. Struggling to find anything but I may just be over complicating things!
View 18 Replies
Jun 20, 2010
how to create C# classes to represent one to many relationships in C#. I have a Customer and an Address table in my database. I also have a Customer class in my C# solution but how do I introduce the multiple address element? Do I have a separate Address class? Do I create a subclass in the Customer class or create a method in Customer called GetAddresses of type List which contains all of the relevant logic? In my code I need to be able to return a customer with all associated addresses and I just cannot picture the best way to achieve this using OOP.
View 9 Replies
Nov 22, 2010
So I am working on an MVC project to put to work the studying I have been doing. I am wrestling with the concept of Database Table relationships and foreign keys. I am working on a simple ecommerce site (displays products, shopping cart, user accounts..etc).
I have the following tables to start out with:
1) Products
2) Categories
I setup the Products and Categories tables to have a ProductId and CategoryId respectively. In my MySQL db, I created a FK on the Products Table to relate to the CategoryId field on the Categories table (I am not sure this was correct to begin).
My expectations for the way the database would handle the table relationship: I didn't want the DB to do anything with the products table if I deleted a category out of the Categories table, or vise versa. The only thing would be that the category field in a Product would be blank (or default) if their category was removed.
Finally, do I have to do anything in my entity classes such as in the Products class, add the ProductId to the Category.ProductId?
Eventually, when I Orders and Users to the project, I can see a relationship where each user -> many orders -> each order has many products -> and each product is in one category.
But I am having a hard time understanding how or if I should be setting up a Foreign key relationship in the two current tables of Products and Categories and if so how to setup my entity class in relation to that FK.
View 1 Replies
Mar 16, 2011
this is a bit of a nomenclature question:what is the correct way to describe the relationships between these classes (the thing that throws me off is the use of generic types here):
[Code]....
View 1 Replies
Jul 14, 2010
I have been experimenting with WebMatrix, specifically the ability to connect to and use SQL CE data.
My question is:
When I am creating a new SQL Compact database with several tables, how do I define relationships between the tables?
The "Relationships" button in WebMatrix is always greyed out. Is that because it is still in Beta? Or am I missing something?
View 5 Replies
May 27, 2010
Using dataloadoptions i have tried the following example
[Code]....
Now i need to ask how can i display Category ID and Category Name of the productID (i am supposing that One product can be in at most one category) by extending the above example Regards.
View 1 Replies
May 27, 2010
Say I have this entity with a lot of attributes. In the input form I have decided to implement a wizard control so I can collect information about this entity in several steps. The problem is that I need to collect information that has been modeled has many to many relationships. I am planning to use a telerik gridview to manage this (add/edit/delete), the problem is where do I store that data since the entity in a insert form is not created on the database yet. OK so I can store all that info in temporary lists residing in the viewstate, waiting for the final submit where I dump all that in the DB, but one of the steps I am collecting files...now storing files in the viewstate is out of the question, same as as storing them in the session...I have been thinking of implementing in a way that the user has to submit some info first (say first 3 steps), commit the data to the database creating the parent entity and then start inserting all the childs entities...but this will get weird as it's confusing since on the first steps you not saving the data to the DB and on the next ones you are commiting directly...
View 1 Replies
Apr 21, 2010
Just a quick question for those more familiar with FluentNHibernate. I've read the quick start things, and the docs on their site, but am still a tad off. Are the following maps correct, in terms of the HasOne / HasMany relationships? If not, correct them, and give me reasons, so I better understand.
C sharp Code:
[code]....
These will eventually go into a convention file, but for now, I just need to know how to code relationships period.
View 4 Replies