Update changes entity framework
When a new course entity is created, it must have a relationship to an existing department. To facilitate this, the scaffolded code includes controller methods and Create and Edit views that include a drop-down list for selecting the department. The drop-down list sets the Course. DepartmentID foreign key property, and that's all the Entity Framework needs in order to load the Department navigation property with the appropriate Department entity.
You'll use the scaffolded code, but change it slightly to add error handling and sort the drop-down list. In CourseController. The PopulateDepartmentsDropDownList method gets a list of all departments sorted by name, creates a SelectList collection for a drop-down list, and passes the collection to the view in a ViewBag property.
The method accepts the optional selectedDepartment parameter that allows the calling code to specify the item that will be selected when the drop-down list is rendered.
The HttpGet Create method calls the PopulateDepartmentsDropDownList method without setting the selected item, because for a new course the department is not established yet:. The HttpGet Edit method sets the selected item, based on the ID of the department that is already assigned to the course being edited:. The HttpPost methods for both Create and Edit also include code that sets the selected item when they redisplay the page after an error:.
This code ensures that when the page is redisplayed to show the error message, whatever department was selected stays selected. Normally the scaffolder doesn't scaffold a primary key because the key value is generated by the database and can't be changed and isn't a meaningful value to be displayed to users.
For Course entities the scaffolder does include an text box for the CourseID field because it understands that the DatabaseGeneratedOption. None attribute means the user should be able enter the primary key value. But it doesn't understand that because the number is meaningful you want to see it in the other views, so you need to add it manually.
Because it's the primary key, it's displayed, but it can't be changed. There's already a hidden field Html. HiddenFor helper for the course number in the Edit view. Adding an Html. LabelFor helper doesn't eliminate the need for the hidden field because it doesn't cause the course number to be included in the posted data when the user clicks Save on the Edit page. Run the Create page display the Course Index page and click Create New and enter data for a new course:.
Click Create. The Course Index page is displayed with the new course added to the list. The department name in the Index page list comes from the navigation property, showing that the relationship was established correctly. Run the Edit page display the Course Index page and click Edit on a course. Change data on the page and click Save. The Course Index page is displayed with the updated course data. When you edit an instructor record, you want to be able to update the instructor's office assignment.
The Instructor entity has a one-to-zero-or-one relationship with the OfficeAssignment entity, which means you must handle the following situations:. Open InstructorController. The scaffolded code here isn't what you want. It's setting up data for a drop-down list, but you what you need is a text box. Replace this method with the following code:. This code drops the ViewBag statement and adds eager loading for the associated OfficeAssignment entity. You can't perform eager loading with the Find method, so the Where and Single methods are used instead to select the instructor.
Replace the HttpPost Edit method with the following code. The following message appears:. Select Show potential fixes , then using System. Gets the current Instructor entity from the database using eager loading for the OfficeAssignment navigation property. This is the same as what you did in the HttpGet Edit method. Update newObj then SaveChanges ; Your solution updates the whole object without having to loop through all the properties.
Make sure the IDs match between the two models and it will update just fine. Show 10 more comments. You can use the AddOrUpdate method: db. Migrations; db. SaveChanges ;. El Mac 2, 7 7 gold badges 30 30 silver badges 50 50 bronze badges. IMO best solution — Norgul. AddOrUpdate is used during database migration, it is highly discouraged to use this method outside of migrations, hence why it's in the Entity. Migrations namespace.
As AdamVincent said, AddOrUpdate method is intended for migrations and it's not suitable for situation when you need only to update existing row. In case when you don't have book with search reference i.
ID it'll create new row and it can be an issue in come cases for example, you have an API which needs to return you NotFound response if you try to call PUT method for non-existing row. Don;t use this unless you know what you are doing!!!!!!!!!!!!!!!! I came back to this again today, can I just warn you all that this is not a good solution for the desired use case — Yusha.
Show 1 more comment. In other words, just change attach to add , and it works for me: public static void SaveBook Model. Add myBook ; ctx. Entry myBook. Modified; ctx. Lauren Rutledge 1, 5 5 gold badges 18 18 silver badges 26 26 bronze badges. Duray Akar Duray Akar 4 4 silver badges 4 4 bronze badges. Add a comment. First ; NewObj. We can not change an existing key. Entry EditedObj.
SetValues NewObj ; context. Jarek Jarek 4 4 silver badges 10 10 bronze badges. You should at least try to answer the question, not just post the code — StaceyGirl. Please make some explanation to the question instead of just leaving a code snippet in order to help the question asker better. According to the EF6 docs : If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified.
Entry existingBlog. Bondolin Bondolin 2, 6 6 gold badges 27 27 silver badges 59 59 bronze badges. Entry con. Property ep. CreateInstance Type. GetType type. GetProperty pi. SetValue tmp, pi. UseSqlServer connString ; base. Juan Juan 1, 13 13 silver badges 19 19 bronze badges. I found a way that works just fine. Find id ; Update. Entry Update. Modified; context. Farhan Farhan 1, 13 13 silver badges 22 22 bronze badges. Add customer ; context.
Entry customer. Chris Rosete Chris Rosete 1, 15 15 silver badges 13 13 bronze badges. Suppose I have a record with 10Mb text property. Will it be sending it to DB every time when I update another property? Consider having multiple tables named First, Second and Third Html.
FirstID Html. SecondID Html. ThirdID Html. Entry first. Modified; datacontext. Pauwelyn Kumar R Kumar R 51 1 1 silver badge 3 3 bronze badges. Add user ; myDb. Attach user ; myDb. Entry user. SaveChanges , it will create an update statement for each entity where there was an actual change, and the statement will only update the modified property.
If no actual changes were made, no updates are made to the database. Notice that each update statement ninjas selectively updates only the property that has changed:. For example, you might want to apply some updates to a set of records, and if any changed, update a timestamp or add a reason for the change. Knowing if an entity has been updated can be determined using context. Entry MyEntity.
0コメント