Search Results

Search found 908 results on 37 pages for 'cascading deletes'.

Page 5/37 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Structuring cascading properties - parent only or parent + entire child graph?

    - by SB2055
    I have a Folder entity that can be Moderated by users. Folders can contain other folders. So I may have a structure like this: Folder 1 Folder 2 Folder 3 Folder 4 I have to decide how to implement Moderation for this entity. I've come up with two options: Option 1 When the user is given moderation privileges to Folder 1, define a moderator relationship between Folder 1 and User 1. No other relationships are added to the db. To determine if the user can moderate Folder 3, I check and see if User 1 is the moderator of any parent folders. This seems to alleviate some of the complexity of handling updates / moved entities / additions under Folder 1 after the relationship has been defined, and reverting the relationship means I only have to deal with one entity. Option 2 When the user is given moderation privileges to Folder 1, define a new relationship between User 1 and Folder 1, and all child entities down to the grandest of grandchildren when the relationship is created, and if it's ever removed, iterate back down the graph to remove the relationship. If I add something under Folder 2 after this relationship has been made, I just copy all Moderators into the new Entity. But when I need to show only the top-level Folders that a user is Moderating, I need to query all folders that have a parent folder that the user does not moderate, as opposed to option 1, where I just query any items that the user is moderating. I think it comes down to determining if users will be querying for all parent items more than they'll be querying child items... if so, then option 1 seems better. But I'm not sure. Is either approach better than the other? Why? Or is there another approach that's better than both? I'm using Entity Framework in case it matters.

    Read the article

  • Why do a small amount of add/deletes take several seconds in EF4?

    - by TomWij
    Using the Entity Framework 4. I have created a Code First database in the past and a piece of code needs to delete and add 16 objects, this takes 6 seconds each. That's 300+ ms for each query! The deletes/adds occur in a foreach scope and there is a SaveChanges() outside the foreach. In the above image you see that each takes 6 seconds, which is 34% of the time, for 16 calls. That doesn't sound normal to me... Why is this and how can I improve the performance? If there is no solution: Are there any workarounds I can use? It would be a pain to rewrite my project...

    Read the article

  • Hibernate cascading: should setting to null on a parent delete children?

    - by EugeneP
    I wonder if Hib works as expected in my case? My Cascading options are set to "all,delete-orphan". Table_A @OneToOne Table_B Table_B @OneToMany Table_C Now it looks like Table_A . getTable_B . getTable_C_Collection() Suppose there are elements in Table_C collection. What I expect from Hibernate: if I set Table_B link to null, then all Table_C collection elements MUST BE DELETED. It does not happen. They become ORPHANED !

    Read the article

  • When Typing on my mac the cursor moves/deletes/replaces text.

    - by David
    Help! I don't know what is happening, with my computer (Macbook Black OSX 1ha0.6.6) but recently whenever I am typing my cursor suddenly moves in the middle of my frase or paragraph, deleting text, replacing words or just closing applications. I don't know what might be the cause but it's driving me crazy. I have disabled typinator (which had worked fine for a couple of months) and looked through the keybindings in SystemPreferencesKeyboardKeyboard Shortcuts. But for have not been able to find any answers. It happens in all apps that require typing. Textmate, Chrome, FIrefox, Texedit, Mail. Does anybody know if there is a way I can review all keyboard shortcuts, to see if the issue lies there or any suggestions? Thanking you dearly Dave

    Read the article

  • How to get Firefox Greasemonkey script to use a local cascading stylesheet?

    - by Umber Ferrule
    What's the correct syntax to link to a CSS file in the same directory as a Greasemonkey JavaScript? I've tried the following but it doesn't work: var cssNode = document.createElement('link'); cssNode.type = 'text/css'; cssNode.rel = 'stylesheet'; cssNode.href = 'example.css'; cssNode.media = 'screen'; cssNode.title = 'dynamicLoadedSheet'; document.getElementsByTagName("head")[0].appendChild(cssNode); If I can get this to work, it would be a lot easier than encasing CSS changes in JavaScript.

    Read the article

  • cascading dropdown value doesn't seem to get posted to my php page?

    - by udaya
    i am using cascading dropdownlist for showing states of a country... I get the country dropdown value but not the state dropdown value.... I am populating state values via ajax... echo $country = $this->input->post('country'); echo $state = $this->input->post('state'); When inspected through firebug it shows all the option values of my state dropdown then why doesn't it get posted? <select onchange="getCity(1,this.value)" name="state"> <option value="0">Select State</option> <option value="1">Andhra Pradesh</option> <option value="2">Arunachal Pradesh</option> <option value="3">Assam</option> <option value="4">Bihar</option> <option value="5">Chandigarh</option> <option value="6">Chhattisgarh</option> <option value="7">Dadra and Nagar Haveli</option> <option value="8">Daman and Diu</option> <option value="9">Delhi</option> <option value="10">Goa</option> <option value="11">Gujarat</option> <option value="12">Haryana</option> <option value="13">Himachal Pradesh</option> <option value="14">Jammu and Kashmir</option> <option value="15">Jharkhand</option> <option value="16">Karnataka</option> <option value="17">Kerala</option> <option value="18">Lakshadweep</option> <option value="19">Madhya Pradesh</option> <option value="20">Maharashtra</option> <option value="21">Manipur</option> <option value="22">Meghalaya</option> <option value="23">Mizoram</option> <option value="24">Nagaland</option> <option value="25">Orissa</option> <option value="26">Puducherry</option> <option value="27">Punjab</option> <option value="28">Rajasthan</option> <option value="29">Sikkim</option> <option value="30">Tamil Nadu</option> <option value="31">Tripura</option> <option value="32">Uttar Pradesh</option> <option value="33">Uttarakhand</option> <option value="34">West Bengal</option> </select>

    Read the article

  • Cascading updates with business key equality: Hibernate best practices?

    - by Traphicone
    I'm new to Hibernate, and while there are literally tons of examples to look at, there seems to be so much flexibility here that it's sometimes very hard to narrow all the options down the best way of doing things. I've been working on a project for a little while now, and despite reading through a lot of books, articles, and forums, I'm still left with a bit of a head scratcher. Any veteran advice would be very appreciated. So, I have a model involving two classes with a one-to-many relationship from parent to child. Each class has a surrogate primary key and a uniquely constrained composite business key. <class name="Container"> <id name="id" type="java.lang.Long"> <generator class="identity"/> </id> <properties name="containerBusinessKey" unique="true" update="false"> <property name="name" not-null="true"/> <property name="owner" not-null="true"/> </properties> <set name="items" inverse="true" cascade="all-delete-orphan"> <key column="container" not-null="true"/> <one-to-many class="Item"/> </set> </class> <class name="Item"> <id name="id" type="java.lang.Long"> <generator class="identity"/> </id> <properties name="itemBusinessKey" unique="true" update="false"> <property name="type" not-null="true"/> <property name="color" not-null="true"/> </properties> <many-to-one name="container" not-null="true" update="false" class="Container"/> </class> The beans behind these mappings are as boring as you can possibly imagine--nothing fancy going on. With that in mind, consider the following code: Container c = new Container("Things", "Me"); c.addItem(new Item("String", "Blue")); c.addItem(new Item("Wax", "Red")); Transaction t = session.beginTransaction(); session.saveOrUpdate(c); t.commit(); Everything works fine the first time, and both the Container and its Items are persisted. If the above code block is executed again, however, Hibernate throws a ConstraintViolationException--duplicate values for the "name" and "owner" columns. Because the new Container instance has a null identifier, Hibernate assumes it is an unsaved transient instance. This is expected but not desired. Since the persistent and transient Container objects have the same business key values, what we really want is to issue an update. It is easy enough to convince Hibernate that our new Container instance is the same as our old one. With a quick query we can get the identifier of the Container we'd like to update, and set our transient object's identifier to match. Container c = new Container("Things", "Me"); c.addItem(new Item("String", "Blue")); c.addItem(new Item("Wax", "Red")); Query query = session.createSQLQuery("SELECT id FROM Container" + "WHERE name = ? AND owner = ?"); query.setString(0, c.getName()); query.setString(1, c.getOwner()); BigInteger id = (BigInteger)query.uniqueResult(); if (id != null) { c.setId(id.longValue()); } Transaction t = session.beginTransaction(); session.saveOrUpdate(c); t.commit(); This almost satisfies Hibernate, but because the one-to-many relationship from Container to Item cascades, the same ConstraintViolationException is also thrown for the child Item objects. My question is: what is the best practice in this situation? It is highly recommended to use surrogate primary keys, and it is also recommended to use business key equality. When you put these two recommendations in to practice together, however, two of the greatest conveniences of Hibernate--saveOrUpdate and cascading operations--seem to be rendered almost completely useless. As I see it, I have only two options: Manually fetch and set the identifier for each object in the mapping. This clearly works, but for even a moderately sized schema this is a lot of extra work which it seems Hibernate could easily be doing. Write a custom interceptor to fetch and set object identifiers on each operation. This looks cleaner than the first option but is rather heavy-handed, and it seems wrong to me that you should be expected to write a plug-in which overrides Hibernate's default behavior for a mapping which follows the recommended design. Is there a better way? Am I making completely the wrong assumptions? I'm hoping that I'm just missing something. Thanks.

    Read the article

  • ADO.NET DataTable/DataRow Thread Safety

    - by Allen E. Scharfenberg
    Introduction A user reported to me this morning that he was having an issue with inconsistent results (namely, column values sometimes coming out null when they should not be) of some parallel execution code that we provide as part of an internal framework. This code has worked fine in the past and has not been tampered with lately, but it got me to thinking about the following snippet: Code Sample lock (ResultTable) { newRow = ResultTable.NewRow(); } newRow["Key"] = currentKey; foreach (KeyValuePair<string, object> output in outputs) { object resultValue = output.Value; newRow[output.Name] = resultValue != null ? resultValue : DBNull.Value; } lock (ResultTable) { ResultTable.Rows.Add(newRow); } (No guarantees that that compiles, hand-edited to mask proprietery information.) Explanation We have this cascading type of locking code other places in our system, and it works fine, but this is the first instance of cascading locking code that I have come across that interacts with ADO .NET. As we all know, members of framework objects are usually not thread safe (which is the case in this situation), but the cascading locking should ensure that we are not reading and writing to ResultTable.Rows concurrently. We are safe, right? Hypothesis Well, the cascading lock code does not ensure that we are not reading from or writing to ResultTable.Rows at the same time that we are assigning values to columns in the new row. What if ADO .NET uses some kind of buffer for assigning column values that is not thread safe--even when different object types are involved (DataTable vs. DataRow)? Has anyone run into anything like this before? I thought I would ask here at StackOverflow before beating my head against this for hours on end :) Conclusion Well, the consensus appears to be that changing the cascading lock to a full lock has resolved the issue. That is not the result that I expected, but the full lock version has not produced the issue after many, many, many tests. The lesson: be wary of cascading locks used on APIs that you do not control. Who knows what may be going on under the covers!

    Read the article

  • How to create a rails habtm that deletes/destroys without error?

    - by Bradley
    I created a simple example as a sanity check and still can not seem to destroy an item on either side of a has_and_belongs_to_many relationship in rails. Whenever I try to delete an object from either table, I get the dreaded NameError / "uninitialized constant" error message. To demonstrate, I created a sample rails app with a Boy class and Dog class. I used the basic scaffold for each and created a linking table called boys_dogs. I then added a simple before_save routine to create a new 'dog' any time a boy was created and establish a relationship, just to get things setup easily. dog.rb class Dog < ActiveRecord::Base has_and_belongs_to_many :Boys end boy.rb class Boy < ActiveRecord::Base has_and_belongs_to_many :Dogs def before_save self.Dogs.build( :name => "Rover" ) end end schema.rb ActiveRecord::Schema.define(:version => 20100118034401) do create_table "boys", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "boys_dogs", :id => false, :force => true do |t| t.integer "boy_id" t.integer "dog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "dogs", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end end I've seen lots of posts here and elsewhere about similar problems, but the solutions are normally using belongs_to and the plural/singular class names being confused. I don't think that is the case here, but I tried switching the habtm statement to use the singular name just to see if it helped (with no luck). I seem to be missing something simple here. The actual error message is: NameError in BoysController#destroy uninitialized constant Boy::Dogs The trace looks like: /Library/Ruby/Gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:105:in const_missing' (eval):3:indestroy_without_callbacks' /Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record/callbacks.rb:337:in destroy_without_transactions' /Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record/transactions.rb:229:insend' ... Thanks.

    Read the article

  • Should I commit or rollback a transaction that creates a temp table, reads, then deletes it?

    - by Triynko
    To select information related to a list of hundreds of IDs... rather than make a huge select statement, I create temp table, insert the ids into it, join it with a table to select the rows matching the IDs, then delete the temp table. So this is essentially a read operation, with no permanent changes made to any persistent database tables. I do this in a transaction, to ensure the temp table is deleted when I'm finished. My question is... what happens when I commit such a transaction vs. let it roll it back? Performance-wise... does the DB engine have to do more work to roll back the transaction vs committing it? Is there even a difference since the only modifications are done to a temp table? Related question here, but doesn't answer my specific case involving temp tables: http://stackoverflow.com/questions/309834/should-i-commit-or-rollback-a-read-transaction

    Read the article

  • How can I do more than one level of cascading deletes in Linq?

    - by Gary McGill
    If I have a Customers table linked to an Orders table, and I want to delete a customer and its corresponding orders, then I can do: dataContext.Orders.DeleteAllOnSubmit(customer.Orders); dataContext.Customers.DeleteOnSubmit(customer); ...which is great. However, what if I also have an OrderItems table, and I want to delete the order items for each of the orders deleted? I can see how I could use DeleteAllOnSubmit to cause the deletion of all the order items for a single order, but how can I do it for all the orders?

    Read the article

  • Gtk, Does deleting builder pointer deletes all the Widgets created using it.

    - by PP
    I am creating builder pointer as follows. GtkBuilder *builder_ptr; builder_ptr = gtk_builder_new(); if( ! gtk_builder_add_from_file(builder_ptr, "Test.glade", &error ) ) printf("\n Error Builder, Exit!\n"); and i am deleting this builder pointer as follows: g_object_unref(G_OBJECT(m_builder)); this builder pointer contains 2-3 GtkWindows and other widgets. So my question is that do i need to delete all the windows in this builder manually when i delete this builder or all the windows will get destroyed when i delete builder pointer. Thanks, PP.

    Read the article

  • code doesnot delete specific extra files but deletes all, also no recursion for directory, help me t

    - by OM The Eternity
    I have to compare two folder structure and with reference of source folder I want to delete all the files/folders present in other destination folder which do not exist in reference source folder, how could i do this? $original = scan_dir_recursive('/var/www/html/copy2'); $mirror = scan_dir_recursive('/var/www/html/copy1'); function scan_dir_recursive($dir) { $all_paths = array(); $new_paths = scandir($dir); foreach ($new_paths as $path) { if ($path == '.' || $path == '..') { continue; } $path = $dir . DIRECTORY_SEPARATOR . $path; if (is_dir($path)) { $all_paths = array_merge($all_paths, scan_dir_recursive($path)); } else { $all_paths[] = $path; } } return $all_paths; } foreach($mirror as $mirr) { if($mirr != '.' && $mirr != '..') { if(!in_array($mirr, $original)) { unlink($mirr); // delete the file } } } The above code shows what i did.. Here My copy1 folder contains extra files than copy2 folders hence i need these extra files to be deleted. Below given output is are arrays of original Mirror and of difference of both.. Original Array ( [0] => /var/www/html/copy2/Copy (5) of New Text Document.txt [1] => /var/www/html/copy2/Copy of New Text Document.txt ) Mirror Array ( [0] => /var/www/html/copy1/Copy (2) of New Text Document.txt [1] => /var/www/html/copy1/Copy (3) of New Text Document.txt [2] => /var/www/html/copy1/Copy (5) of New Text Document.txt ) Difference Array ( [0] => /var/www/html/copy1/Copy (2) of New Text Document.txt [1] => /var/www/html/copy1/Copy (3) of New Text Document.txt [2] => /var/www/html/copy1/Copy (5) of New Text Document.txt ) when i iterate a loop to delete on difference array all files has to be deleted as per displayed output.. how can i rectify this.. the loop for deletion is given below. $dirs_to_delete = array(); foreach ($diff_path as $path) { if (is_dir($path)) { $dirs_to_delete[] = $path; } else { unlink($path); } } while ($dir = array_pop($dirs_to_delete)) { rmdir($dir); }

    Read the article

  • Cascading dropdownlist jQuery does not retain value on post back.

    - by John Smith
    I have two html select server control on an add data form page. the user selects a value in the first html select server control and then values are populated into the second html select server control with jquery. The problem is when a a user clicks the save button and the page posts back, the values are no longer in the drop down list populated by jQuery. The drop downlist is a html server control, shouldn't it retain the values on post-back? How can I retain the values and save the selected value to the database? $(document).ready(function() { $("#<%=ddlCourseWare.ClientID %>").change(function() { var courseWareId = this.value; try { $.ajax({ type: "POST", url: "Left_SubCategory.aspx/GetTabData", data: "{courseWareId:" + courseWareId + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { var result = json_parse(data.d); $("#<%=ddlTabType.ClientID %>")[0].innerHTML = ''; if (result.length > 0) { $.each(result, function(key, item) { $("#<%=ddlTabType.ClientID %>").append($("<option></option>").val(item.id).html(item.TabName)); }); } else { $("#<%=ddlTabType.ClientID %>").append($("<option></option>").val('0').html('--Select--')); } }, error: function(request, status, error) { alert(request.responseText); } }); } catch (ex) { alert(ex); } }); }); HTML <select id="ddlCourseWare" name="ddlCourseWare" runat="server" Width="230px" class="TextBox" Height="18px" > <select id="ddlTabType" name="ddlTabType" runat="server" Width="230px" class="TextBox" Height="18px" onchange="BindMainCat();"> <option>--Select--</option> </select> C# private void BindCourseWare() { ddlCourseWare.DataSource = courseWare.GetCourseWare(); ddlCourseWare.DataTextField = "CourseWareType"; ddlCourseWare.DataValueField = "id"; ddlCourseWare.DataBind(); ddlCourseWare.Items.Insert(0, "----Select Course Ware----"); } [WebMethod] public static string GetTabData(int courseWareId) { var result = new CourseWare().GetCourseTabByCoursewareId(courseWareId); JavaScriptSerializer json_tabs = new JavaScriptSerializer(); string jsonArray_tabs = json_tabs.Serialize(result); return jsonArray_tabs; } protected void btnSave_Click(object sender, EventArgs e) { int mainCategoryID1 = int.Parse(ddlTabType.Value); // not working int mainCategoryID2 = int.Parse(Request["ctl00$ContentPlaceHolder1$ddlTabType"]); // working but always return same value means the upper value (selected index 1) }

    Read the article

  • How to load cascading style sheet into C# object?

    - by Krishnaraj
    Hello, I am developing a web application, where i want to give freedom of changing style elements of css linked to a page via an admin screen. So I am wondering is there any way I can load CSS file into a C# object or into XML passable formate and update it from the admin screen inputs? Thank you, Krishnaraj

    Read the article

  • How to make Unit Tests to make sure stored procedure is deleting row from the database?

    - by aspdotnetuser
    I'm new to unit testing and I need some help with the following. I have created a small project to help me learn how to make Unit Tests. The functionality for one of the forms in my application deletes a user from the User table (and other rows in mapping tables). Currently, the unit test I have created to test this sets up the required objects and then calls the business rules method (passing in the user id) which calls the data access method to execute the stored procedure that deletes the rows in the tables. Is this the correct method to test whether something is being deleted successfully? Should the unit test / setup method first insert some test data which the unit test then deletes?

    Read the article

  • Is it reasonable for REST resources to be singular and plural?

    - by Evan
    I have been wondering if, rather than a more traditional layout like this: api/Products GET // gets product(s) by id PUT // updates product(s) by id DELETE // deletes (product(s) by id POST // creates product(s) Would it be more useful to have a singular and a plural, for example: api/Product GET // gets a product by id PUT // updates a product by id DELETE // deletes a product by id POST // creates a product api/Products GET // gets a collection of products by id PUT // updates a collection of products by id DELETE // deletes a collection of products (not the products themselves) POST // creates a collection of products based on filter parameters passed So, to create a collection of products you might do: POST api/Products {data: filters} // returns api/Products/<id> And then, to reference it, you might do: GET api/Products/<id> // returns array of products In my opinion, the main advantage of doing things this way is that it allows for easy caching of collections of products. One might, for example, put a lifetime of an hour on collections of products, thus drastically reducing the calls on a server. Of course, I currently only see the good side of doing things this way, what's the downside?

    Read the article

  • Windows system restore deletes various executables and *.js files. How does it decide which files to delete?

    - by Leftium
    I restored my system from a Windows System Restore point. It solved some issues I was having, but introduced other strange problems (like my optical drive disappeared). One thing that surprised me was several files from my Web2Py installation were deleted: the executables and *.js files; possibly some others (like favicon.ico). I did not expect this because Web2Py is basically a portable, standalone application. You just unzip it and run the executable inside, so nothing should be registered with Windows. My question is: what files does Windows system restore delete, and how does it decide this? I'm just wondering what other files I'm missing and if there's a way to get restore them (without rolling back the restore point). Perhaps it scans for certain files types (like exe, js, ico, dll) with a creation date that was after the restore point creation date? Some other people who experienced a similar problem: Dropbox: Lost Files User files missing after run system restore. update: I found some more references on how Windows System Restore works: Understanding how System Restore in Windows Vista treats executable files Why Vista's System Restore is Dangerous and What to do About it

    Read the article

  • Where'd My Data Go? (and/or...How Do I Get Rid of It?)

    - by David Paquette
    Want to get a better idea of how cascade deletes work in Entity Framework Code First scenarios? Want to see it in action? Stick with us as we quickly demystify what happens when you tell your data context to nuke a parent entity. This post is authored by Calgary .NET User Group Leader David Paquette with help from Microsoft MVP in Asp.Net James Chambers. We got to spend a great week back in March at Prairie Dev Con West, chalk full of sessions, presentations, workshops, conversations and, of course, questions.  One of the questions that came up during my session: "How does Entity Framework Code First deal with cascading deletes?". James and I had different thoughts on what the default was, if it was different from SQL server, if it was the same as EF proper and if there was a way to override whatever the default was.  So we built a set of examples and figured out that the answer is simple: it depends.  (Download Samples) Consider the example of a hockey league. You have several different entities in the league including games, teams that play the games and players that make up the teams. Each team also has a mascot.  If you delete a team, we need a couple of things to happen: The team, games and mascot will be deleted, and The players for that team will remain in the league (and therefore the database) but they should no longer be assigned to a team. So, let's make this start to come together with a look at the default behaviour in SQL when using an EDMX-driven project. The Reference – Understanding EF's Behaviour with an EDMX/DB First Approach First up let’s take a look at the DB first approach.  In the database, we defined 4 tables: Teams, Players, Mascots, and Games.  We also defined 4 foreign keys as follows: Players.Team_Id (NULL) –> Teams.Id Mascots.Id (NOT NULL) –> Teams.Id (ON DELETE CASCADE) Games.HomeTeam_Id (NOT NULL) –> Teams.Id Games.AwayTeam_Id (NOT NULL) –> Teams.Id Note that by specifying ON DELETE CASCADE for the Mascots –> Teams foreign key, the database will automatically delete the team’s mascot when the team is deleted.  While we want the same behaviour for the Games –> Teams foreign keys, it is not possible to accomplish this using ON DELETE CASCADE in SQL Server.  Specifying a ON DELETE CASCADE on these foreign keys would cause a circular reference error: The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree that contains no circular references. No table can appear more than one time in the list of all cascading referential actions that result from the DELETE or UPDATE – MSDN When we create an entity data model from the above database, we get the following:   In order to get the Games to be deleted when the Team is deleted, we need to specify End1 OnDelete action of Cascade for the HomeGames and AwayGames associations.   Now, we have an Entity Data Model that accomplishes what we set out to do.  One caveat here is that Entity Framework will only properly handle the cascading delete when the the players and games for the team have been loaded into memory.  For a more detailed look at Cascade Delete in EF Database First, take a look at this blog post by Alex James.   Building The Same Sample with EF Code First Next, we're going to build up the model with the code first approach.  EF Code First is defined on the Ado.Net team blog as such: Code First allows you to define your model using C# or VB.Net classes, optionally additional configuration can be performed using attributes on your classes and properties or by using a Fluent API. Your model can be used to generate a database schema or to map to an existing database. Entity Framework Code First follows some conventions to determine when to cascade delete on a relationship.  More details can be found on MSDN: If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null. The multiplicity and cascade delete behavior detected by convention can be overridden by using the fluent API. For more information, see Configuring Relationships with Fluent API (Code First). Our DbContext consists of 4 DbSets: public DbSet<Team> Teams { get; set; } public DbSet<Player> Players { get; set; } public DbSet<Mascot> Mascots { get; set; } public DbSet<Game> Games { get; set; } When we set the Mascot –> Team relationship to required, Entity Framework will automatically delete the Mascot when the Team is deleted.  This can be done either using the [Required] data annotation attribute, or by overriding the OnModelCreating method of your DbContext and using the fluent API. Data Annotations: public class Mascot { public int Id { get; set; } public string Name { get; set; } [Required] public virtual Team Team { get; set; } } Fluent API: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Mascot>().HasRequired(m => m.Team); } The Player –> Team relationship is automatically handled by the Code First conventions. When a Team is deleted, the Team property for all the players on that team will be set to null.  No additional configuration is required, however all the Player entities must be loaded into memory for the cascading to work properly. The Game –> Team relationship causes some grief in our Code First example.  If we try setting the HomeTeam and AwayTeam relationships to required, Entity Framework will attempt to set On Cascade Delete for the HomeTeam and AwayTeam foreign keys when creating the database tables.  As we saw in the database first example, this causes a circular reference error and throws the following SqlException: Introducing FOREIGN KEY constraint 'FK_Games_Teams_AwayTeam_Id' on table 'Games' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. To solve this problem, we need to disable the default cascade delete behaviour using the fluent API: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Mascot>().HasRequired(m => m.Team); modelBuilder.Entity<Team>() .HasMany(t => t.HomeGames) .WithRequired(g => g.HomeTeam) .WillCascadeOnDelete(false); modelBuilder.Entity<Team>() .HasMany(t => t.AwayGames) .WithRequired(g => g.AwayTeam) .WillCascadeOnDelete(false); base.OnModelCreating(modelBuilder); } Unfortunately, this means we need to manually manage the cascade delete behaviour.  When a Team is deleted, we need to manually delete all the home and away Games for that Team. foreach (Game awayGame in jets.AwayGames.ToArray()) { entities.Games.Remove(awayGame); } foreach (Game homeGame in homeGames) { entities.Games.Remove(homeGame); } entities.Teams.Remove(jets); entities.SaveChanges();   Overriding the Defaults – When and How To As you have seen, the default behaviour of Entity Framework Code First can be overridden using the fluent API.  This can be done by overriding the OnModelCreating method of your DbContext, or by creating separate model override files for each entity.  More information is available on MSDN.   Going Further These were simple examples but they helped us illustrate a couple of points. First of all, we were able to demonstrate the default behaviour of Entity Framework when dealing with cascading deletes, specifically how entity relationships affect the outcome. Secondly, we showed you how to modify the code and control the behaviour to get the outcome you're looking for. Finally, we showed you how easy it is to explore this kind of thing, and we're hoping that you get a chance to experiment even further. For example, did you know that: Entity Framework Code First also works seamlessly with SQL Azure (MSDN) Database creation defaults can be overridden using a variety of IDatabaseInitializers  (Understanding Database Initializers) You can use Code Based migrations to manage database upgrades as your model continues to evolve (MSDN) Next Steps There's no time like the present to start the learning, so here's what you need to do: Get up-to-date in Visual Studio 2010 (VS2010 | SP1) or Visual Studio 2012 (VS2012) Build yourself a project to try these concepts out (or download the sample project) Get into the community and ask questions! There are a ton of great resources out there and community members willing to help you out (like these two guys!). Good luck! About the Authors David Paquette works as a lead developer at P2 Energy Solutions in Calgary, Alberta where he builds commercial software products for the energy industry.  Outside of work, David enjoys outdoor camping, fishing, and skiing. David is also active in the software community giving presentations both locally and at conferences. David also serves as the President of Calgary .Net User Group. James Chambers crafts software awesomeness with an incredible team at LogiSense Corp, based in Cambridge, Ontario. A husband, father and humanitarian, he is currently residing in the province of Manitoba where he resists the urge to cheer for the Jets and maintains he allegiance to the Calgary Flames. When he's not active with the family, outdoors or volunteering, you can find James speaking at conferences and user groups across the country about web development and related technologies.

    Read the article

  • Ajax Control Toolkit November 2011 Release

    - by Stephen Walther
    I’m happy to announce the November 2011 Release of the Ajax Control Toolkit. This release introduces a new Balloon Popup control and several enhancements to the existing Tabs control including support for on-demand loading of tab content, support for vertical tabs, and support for keyboard tab navigation. We also fixed the top-voted bugs associated with the Tabs control reported at CodePlex.com. You can download the new release by visiting the CodePlex website: http://AjaxControlToolkit.CodePlex.com Alternatively, the fast and easy way to get the latest release of the Ajax Control Toolkit is to use NuGet. Open your Library Package Manager console in Visual Studio 2010 and type: After you install the Ajax Control Toolkit through NuGet, please do a Rebuild of your project (the menu option Build, Rebuild). After you do a Rebuild, the ajaxToolkit prefix will appear in Intellisense: Using the Balloon Popup Control Why a new Balloon Popup control? The Balloon Popup control is the second most requested new feature for the Ajax Control Toolkit according to CodePlex votes: The Balloon Popup displays a message in a balloon when you shift focus to a control, click a control, or hover over a control. You can use the Balloon Popup, for example, to display instructions for TextBoxes which appear in a form: Here’s the code used to create the Balloon Popup: <ajaxToolkit:ToolkitScriptManager ID="tsm1" runat="server" /> <asp:TextBox ID="txtFirstName" Runat="server" /> <asp:Panel ID="pnlFirstNameHelp" runat="server"> Please enter your first name </asp:Panel> <ajaxToolkit:BalloonPopupExtender TargetControlID="txtFirstName" BalloonPopupControlID="pnlFirstNameHelp" BalloonSize="Small" UseShadow="true" runat="server" /> You also can use the Balloon Popup to explain hard to understand words in a text document: Here’s how you display the Balloon Popup when you hover over the link: The point of the conversation was <asp:HyperLink ID="lnkObfuscate" Text="obfuscated" CssClass="hardWord" runat="server" /> by his incessant coughing. <ajaxToolkit:ToolkitScriptManager ID="tsm1" runat="server" /> <asp:Panel id="pnlObfuscate" Runat="server"> To bewilder or render something obscure </asp:Panel> <ajaxToolkit:BalloonPopupExtender TargetControlID="lnkObfuscate" BalloonPopupControlID="pnlObfuscate" BalloonStyle="Cloud" UseShadow="true" DisplayOnMouseOver="true" Runat="server" />   There are four important properties which you need to know about when using the Balloon Popup control: BalloonSize – The three balloon sizes are Small, Medium, and Large. BalloonStyle -- The two built-in styles are Rectangle and Cloud. UseShadow – When true, a drop shadow appears behind the popup. Position – Can have the values Auto, BottomLeft, BottomRight, TopLeft, TopRight. When set to Auto, which is the default, the Balloon Popup will appear where it has the most screen real estate. The following screenshots illustrates how these settings affect the appearance of the Balloon Popup: Customizing the Balloon Popup You can customize the appearance of the Balloon Popup by creating your own Cascading Style Sheet and Sprite. The Ajax Control Toolkit sample site includes a sample of a custom Oval Balloon Popup style: This custom style was created by using a custom Cascading Style Sheet and image. You point the Balloon Popup at a custom Cascading Style Sheet and Cascading Style Sheet class by using the CustomCssUrl and CustomClassName properties like this: <asp:TextBox ID="txtCustom" autocomplete="off" runat="server" /> <br /> <asp:Panel ID="Panel3" runat="server"> This is a custom BalloonPopupExtender style created with a custom Cascading Style Sheet. </asp:Panel> <ajaxToolkit:BalloonPopupExtender ID="bpe1" TargetControlID="txtCustom" BalloonPopupControlID="Panel3" BalloonStyle="Custom" CustomCssUrl="CustomStyle/BalloonPopupOvalStyle.css" CustomClassName="oval" UseShadow="true" runat="server" />   Learn More about the Balloon Popup To learn more about the Balloon Popup control, visit the sample page for the Balloon Popup at the Ajax Control Toolkit sample site: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/BalloonPopup/BalloonPopupExtender.aspx Improvements to the Tabs Control In this release, we introduced several important new features for the existing Tabs control. We also fixed all of the top-voted bugs for the Tabs control. On-Demand Loading of Tab Content Here is the scenario. Imagine that you are using the Tabs control in a Web Forms page. The Tabs control displays two tabs: Customers and Products. When you click the Customers tab then you want to see a list of customers and when you click on the Products tab then you want to see a list of products. In this scenario, you don’t want the list of customers and products to be retrieved from the database when the page is initially opened. The user might never click on the Products tab and all of the work to load the list of products from the database would be wasted. In this scenario, you want the content of a tab panel to be loaded on demand. The products should only be loaded from the database and rendered to the browser when you click the Products tab and not before. The Tabs control in the November 2011 Release of the Ajax Control Toolkit includes a new property named OnDemand. When OnDemand is set to the value True, a tab panel won’t be loaded until you click its associated tab. Here is the code for the aspx page: <ajaxToolkit:ToolkitScriptManager ID="tsm1" runat="server" /> <ajaxToolkit:TabContainer ID="tabs" OnDemand="false" runat="server"> <ajaxToolkit:TabPanel HeaderText="Customers" runat="server"> <ContentTemplate> <h2>Customers</h2> <asp:GridView ID="grdCustomers" DataSourceID="srcCustomers" runat="server" /> <asp:SqlDataSource ID="srcCustomers" SelectCommand="SELECT * FROM Customers" ConnectionString="<%$ ConnectionStrings:StoreDB %>" runat="server" /> </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel HeaderText="Products" runat="server"> <ContentTemplate> <h2>Products</h2> <asp:GridView ID="grdProducts" DataSourceID="srcProducts" runat="server" /> <asp:SqlDataSource ID="srcProducts" SelectCommand="SELECT * FROM Products" ConnectionString="<%$ ConnectionStrings:StoreDB %>" runat="server" /> </ContentTemplate> </ajaxToolkit:TabPanel> </ajaxToolkit:TabContainer> Notice that the TabContainer includes an OnDemand=”True” property. The Tabs control contains two Tab Panels. The first tab panel uses a DataGrid and SqlDataSource to display a list of customers and the second tab panel uses a DataGrid and SqlDataSource to display a list of products. And here is the code-behind for the page: using System; using System.Diagnostics; using System.Web.UI.WebControls; namespace ACTSamples { public partial class TabsOnDemand : System.Web.UI.Page { protected override void OnInit(EventArgs e) { srcProducts.Selecting += new SqlDataSourceSelectingEventHandler(srcProducts_Selecting); } void srcProducts_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { Debugger.Break(); } } } The code-behind file includes an event handler for the Products SqlDataSource Selecting event. The handler breaks into the debugger by calling the Debugger.Break() method. That way, we can know when the Products SqlDataSource actually retrieves the list of products. When the OnDemand property has the value False then the Selecting event handler is called immediately when the page is first loaded. The contents of all of the tabs are loaded (and the contents of the unselected tabs are hidden) when the page is first loaded. When the OnDemand property has the value True then the Selecting event handler is not called when the page is first loaded. The event handler is not called until you click on the Products tab. If you never click on the Products tab then the list of products is never retrieved from the database. If you want even more control over when the contents of a tab panel gets loaded then you can use the TabPanel OnDemandMode property. This property accepts the following three values: None – Never load the contents of the tab panel again after the page is first loaded. Once – Wait until the tab is selected to load the contents of the tab panel Always – Load the contents of the tab panel each and every time you select the tab. There is a live demonstration of the OnDemandMode property here in the sample page for the Tabs control: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Tabs/Tabs.aspx Displaying Vertical Tabs With the November 2011 Release, the Tabs control now supports vertical tabs. To create vertical tabs, just set the TabContainer UserVerticalStripPlacement property to the value True like this: <ajaxToolkit:TabContainer ID="tabs" OnDemand="false" UseVerticalStripPlacement="true" runat="server"> <ajaxToolkit:TabPanel ID="TabPanel1" HeaderText="First Tab" runat="server"> <ContentTemplate> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </p> </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel ID="TabPanel2" HeaderText="Second Tab" runat="server"> <ContentTemplate> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </p> </ContentTemplate> </ajaxToolkit:TabPanel> </ajaxToolkit:TabContainer> In addition, you can use the TabStripPlacement property to control whether the tab strip appears at the left or right or top or bottom of the tab panels: Tab Keyboard Navigation Another highly requested feature for the Tabs control is support for keyboard navigation. The Tabs control now supports the arrow keys and the Home and End keys. In order for the arrow keys to work, you must first move focus to the tab control on the page by either clicking on a tab with your mouse or repeatedly hitting the Tab key. You can try out the new keyboard navigation support by trying any of the demos included in the Tabs sample page: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Tabs/Tabs.aspx Summary I hope that you take advantage of the new Balloon Popup control and the new features which we introduced for the Tabs control. We added a lot of new features to the Tabs control in this release including support for on-demand tabs, support for vertical tabs, and support for tab keyboard navigation. I want to thank the developers on the Superexpert team for all of the hard work which they put into this release.

    Read the article

  • SQL SERVER – Not Possible – Delete From Multiple Table – Update Multiple Table in Single Statement

    - by pinaldave
    There are two questions which I get every single day multiple times. In my gmail, I have created standard canned reply for them. Let us see the questions here. I want to delete from multiple table in a single statement how will I do it? I want to update multiple table in a single statement how will I do it? The answer is – No, You cannot and you should not. SQL Server does not support deleting or updating from two tables in a single update. If you want to delete or update two different tables – you may want to write two different delete or update statements for it. This method has many issues – from the consistency of the data to SQL syntax. Now here is the real reason for this blog post – yesterday I was asked this question again and I replied my canned answer saying it is not possible and it should not be any way implemented that day. In the response to my reply I was pointed out to my own blog post where user suggested that I had previously mentioned this is possible and with demo example. Let us go over my conversation – you may find it interesting. Let us call the user DJ. DJ: Pinal, can we delete multiple table in a single statement or with single delete statement? Pinal: No, you cannot and you should not. DJ: Oh okey, if that is the case, why do you suggest to do that? Pinal: (baffled) I am not suggesting that. I am rather suggesting that it is not possible and it should not be possible. DJ: Hmm… but in that case why did you blog about it earlier? Pinal: (What?) No, I did not. I am pretty confident. DJ: Well, I am confident as well. You did. Pinal: In that case, it is my word against your word. Isn’t it? DJ: I have proof. Do you want to see it that you suggest it is possible? Pinal: Yes, I will be delighted too. (After 10 Minutes) DJ: Here are not one but two of your blog posts which talks about it - SQL SERVER – Curious Case of Disappearing Rows – ON UPDATE CASCADE and ON DELETE CASCADE – Part 1 of 2 SQL SERVER – Curious Case of Disappearing Rows – ON UPDATE CASCADE and ON DELETE CASCADE – T-SQL Example – Part 2 of 2 Pinal: Oh! DJ: I know I was correct. Pinal: Well, oh man, I did not mean there what you mean here. DJ: I did not understand can you explain it further. Pinal: Here we go. The example in the other blog is the example of the cascading delete or cascading update. I think you may want to understand the concept of the foreign keys and cascading update/delete. The concept of cascading exists to maintain data integrity. If there primary keys get deleted the update or delete reflects on the foreign key table to maintain the key integrity and data consistency. SQL Server follows ANSI Entry SQL with regard to referential integrity between PrimaryKey and ForeignKey columns which requires the inserting, updating, and deleting of data in related tables to be restricted to values that preserve the integrity. This is all together different concept than deleting multiple values in a single statement. When I hear that someone wants to delete or update multiple table in a single statement what I assume is something very similar to following. DELETE/UPDATE Table 1 (cols) Table 2 (cols) VALUES … which is not valid statement/syntax as well it is not ASNI standards as well. I guess, after this discussion with DJ, I realize I need to do a blog post so I can add the link to this blog post in my canned answer. Well, it was a fun conversation with DJ and I hope it the message is very clear now. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Joins, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Le Web bientôt doté d'un nouveau langage ? CAS s'inspire du CSS pour proposer une définition des attributs des balises HTML dans une feuille

    Le Web bientôt doté d'un nouveau langage ? CAS s'inspire du CSS pour proposer une définition des attributs des balises HTML dans une feuille Tab Atkins Jr, un représentant de Google au sein du W3C (World Wide Web Consortium) vient de proposer à l'organisme un nouveau langage de script pour normalisation. Le langage CAS pour Cascading Attribute Sheets s'inspire grandement du CSS (Cascading Style Sheets), à la différence qu'il est basé sur un concept d'attributs HTML. L'idée de base autour de ce nouveau langage est que tout comme avec le CSS, les développeurs pourront définir dans un fichier des attributs pour les balises HTML, qui seront directement appliqués à l'ensemble ...

    Read the article

  • How do large blobs affect SQL delete performance, and how can I mitigate the impact?

    - by Max Pollack
    I'm currently experiencing a strange issue that my understanding of SQL Server doesn't quite mesh with. We use SQL as our file storage for our internal storage service, and our database has about half a million rows in it. Most of the files (86%) are 1mb or under, but even on fresh copies of our database where we simply populate the table with data for the purposes of a test, it appears that rows with large amounts of data stored in a BLOB frequently cause timeouts when our SQL Server is under load. My understanding of how SQL Server deletes rows is that it's a garbage collection process, i.e. the row is marked as a ghost and the row is later deleted by the ghost cleanup process after the changes are copied to the transaction log. This suggests to me that regardless of the size of the data in the blob, row deletion should be close to instantaneous. However when deleting these rows we are definitely experiencing large numbers of timeouts and astoundingly low performance. In our test data set, its files over 30mb that cause this issue. This is an edge case, we don't frequently encounter these, and even though we're looking into SQL filestream as a solution to some of our problems, we're trying to narrow down where these issues are originating from. We ARE performing our deletes inside of a transaction. We're also performing updates to metadata such as file size stats, but these exist in a separate table away from the file data itself. Hierarchy data is stored in the table that contains the file information. Really, in the end it's not so much what we're doing around the deletes that matters, we just can't find any references to low delete performance on rows that contain a large amount of data in a BLOB. We are trying to determine if this is even an avenue worth exploring, or if it has to be one of our processes around the delete that's causing the issue. Are there any situations in which this could occur? Is it common for a database server to come to the point of complete timeouts when many of these deletes are occurring simultaneously? Is there a way to combat this issue if it exists? (cross-posted from StackOverflow )

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >