C# - Deleting Selected Relations In Many-to-many Relationship In EF?
Mar 13, 2011
In SQL, I have:[Bands] 1 ---- * [BandsGenres] * ---- 1 [Genres]In my EF layer, it translates to:[Bands] * ---- * [Genres](BandsGenres is BandId and GenreId)My problem is, I can't seem to figure out how to delete just the selected relationships I need. Basically, I'm trying to update a list of type Genre for a band. A list of Guids is passed in and I'm able to get those using joins. However, the .Remove() method isn't removing the old genres and adding the new ones. I tried using .Attach(g) and .DeleteObject(g) but that removed the actual Genre (from Genres) instead of just the relationship.
[code]...
How can I delete/add or update my list of genre relationships for a band, given a list of genre IDs?
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.
i have a problem executing an insert query. whenever i try to insert i have an exeption telling me it cant execute because a record needed in another table; where i select a value form that other table according a listbox, and then insert it into this table. here is a sample of my code:
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|emp2.mdb");
int a = 0; conn.Open(); string sqlcmd = "select id from nationality where descreption = '" + DropDownList1.Text + "'"; OleDbCommand readNatCmd = new OleDbCommand(sqlcmd, conn); OleDbDataReader readerNat = readNatCmd.ExecuteReader(); while (readerNat.Read()) { a = readerNat.GetInt32(0); } readerNat.Close(); conn.Close(); string saveEmpcmd = @"insert into employee " + "(nationality) " + "values (@nationality)"; OleDbCommand objCmd = new OleDbCommand(saveEmpcmd, conn); objCmd.Parameters.AddWithValue("@nationality", a); conn.Open(); objCmd.ExecuteNonQuery(); conn.Close();
now, the form executes with no errors, but it catches an exeption caused by the ExecuteNonQuery funtion; here it is in details:
System.Data.OleDb.OleDbException: You cannot add or change a record because a related record is required in table 'nationality'. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at Default2.Button1_Click(Object sender, EventArgs e) in c:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005WebSitesempDefault2.aspx.cs:line 305
when i remove the relation between the tables, the exeption isnt catched anymore, but the value stored in the employee table is 0 how can i solve this?
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(); } }
i am currently working on an asp.net mvc 2 web app using LinqToSQL. I would like to handle a scenario where a user comes form a country and for this i have set the users - countries db relationship and in my user model i have a CountryId property.
I would like to display the country name on my users display view, so i tried fetching the country name like this: User.Country.Name, but an exception occurs that i cannot access a disposed object. I understand that this is caused by the way i handle my users repository and service.
This the repository users code:
[Code]....
This is the service users code (the repository is not class level property, but a local one that gets dipsosed immediately after calling it):
[Code]....
So, how could i handle such a scenario, where i would like the Country model to be also fetched in order to use it later? Should i convert the repository model a class level proprty in order not to get disposed?
Is there some kind of simple database system that uses simple text or xml files for data storage? I just need some basic functionality like update,delete, insert, simple constraints and relations.For the project that I have now using SQL Server would be too heavyweight and I have never really liked it anyway.
need Users to be able to be friends with other Users (Users are kept in the User table) im trying to create a "Friends" table so they can relate to one another.I need the UserID stored along with FriendID, UserID is of the current user and FriendID is related to the UserID of the friend. ARGh so confusing. Im getting lost even talking about it again, basically the way ive written my code i need the FriendID to relate to the UserID of the user table so i can find the person im after so I can display there credentials on the current "UserID" page but I also need some way to find out all the current UserIDs friends
i m developing an inventory module in which i have a GRN(Goods Received Note) form, the user opens the form and enter the items which are coming from itemMaster table. I want to add the grn entry in a table named GRN and all its respective item details in other table and also want to update the instock quantity in item Master table. how can i achive this there are multiple items in a grid in grn form which are to be stored in a table and only 1entry of grn in grn table and also update the instock Qty in the itemMaster Table,,...i ned write my logic using Stored procedures and ADO.NET i m totally confused
I make ASP.NET MVC3 application for spa and I've encoutered problem with M:N relationship. I've got this model Each Insurance Company has different pricing for each patient medical indication, so sample data looks like this:
IC Indication Patient IC1 Indication1 Patient1 Patient2 Indication2 Patient3
[Code]....
And I don't know how to make Edit with possibility of changing not only Indication but IC to.
the developer who wrote this code is no longer with us and there are absolutely no comments whatsoever for us to know whats happening. Me and my other co-worker are just learning .net and hence not that much experts. can some one please tell us what the code does in both the files below and how they are related to each other ( we are very +VE that they both are related) first file. its called products.aspx. the code is below
Can someone explain me what is is the relationship between App Domain and thread? msdn says "threads are free to cross application domain boundaries; a new thread is not created for each application domain." suppose there is one thread t inside Appdomain a1 .there is an another App domain a2 .thread t can cross to a2 from a1 means it can access a2 memory area If thread can cross the app domain boundaries share the memory space then how application domain isolation is still there?
I have to create a very simple database driven website ( for a project ) with basic features like a login system, etc. I have completed most of the basic tasks required, but there is one section that is asking me to 'Use persistence to maintain state/relationship'.
I have read a few articles and videos about persistence but I don't understand its benefits and why and how it should be used. Can anyone point me towards a site that explains how to implement state persistence in a simple way. I don't need anything advanced just a very simple way of integrating this into a very simple site to say its been done.
I think I'm just after advice on best practice with this! I have a database which has 2 tables. The first table has ID, Name, Address and the second table has ID and JobType. Table 02 can list multiple types of JobType so we could have
Table01:
1. D Smith. Address01 2. S.Jones. Address02
Table02
1. Accounts 1. Sales Ledger 1. Chartered Accountant 2. IT 2. Web Design 2. Graphic Design 2. 1st line support
A join gets them together and all works perfectly.However, the content will be updated when some one fills in a web form. Do get the form to send results to both tables, I assume I have to open the database twice or can I open it once and open each table one at a time? I know I could practice this and not ask the question but I am interested to know what is the most efficient way. I would also need to know what ID to use. So when I populate Table02 it uses the correct ID from Table01. At the moment Table01 ID field is incremented automatically. Would you suggest I always assign the ID myself, or would I need to query the database, find out what ID number is currently in use and then increment it by 1 and assign the new number to an ID variable which then populates the Table's Field? In which case, am I opening the database again or trying to perform all 2/3 stages in one go?
I want to display details STRONGLY TYPE In a view this would be done as normal through the list, hiting the details link. however a table of notes is connected to the main table of info. i want to us the id of the main table item to list all the notes that have been entered about the record in the main table. how do i do this
I'm trying to understand the relationship between assemblies, namespaces and classes. Can anyone help explain or point me to a usefule link?
1. I understand that an assembly is typicall a dll or an exe (perhaps other files also). Does each project compilation produce only 1 dll? Or is the number of DLL dictated by something completely different?
2. I read each assembly can contain multiple classes. Asingle assembly can contain classes for multiple namespaces, and asingle namespace can span multiple assemblies.
I have an ASP.NET project where I want to keep the membership (SQL Provider) in a separate database and the Roles/Profiles will be per application.QuestionWhat is the KEY that relates between the Membership database and the Roles/Profile database? Is it the UserID or UserName?I opened up the tables in separate expolrer and notice the UserID is different in the Membership database from that in the application Roles database.
i am working with multiple table with some same columns, so here i want to use the concept of primary key and foreign key.primary key is very easy to put on any fields but, i dont know how to give foreign key and how to create relationship between same fields of two table.
I've used aspnet_Profile and I add new values. In the field "PropertyNames" I added value "DomainId". In the field "PropertyValuesStrings" I added value I get from the table "tbl_Domain.
How do I connect aspnet_profile table, column "PropertyValuesStrings"with tbl_Domain, column 'Id' primary key.
I have a database which contain job ads/ I have one table "dbo.tbl_jobadvert" which contains the ad itself and another table "dbo.tbl_jobFiles" which contains the path of the documents uploaded in relations to the job advert ( application form, job description, etc )