Missing knowledge points during development (1)
1. Delete EF cascade operations
By default, CodeFirst sets the deletion rule as cascade in the foreign key constraint (the update rule is not set as cascade by default)
If only navigation attributes are defined, such
Public virtual CategoryCategory {get; set ;}
The foreign key is not displayed, as shown in figure
Public int CategoryId {get; set ;}
CodeFirst does not set the deletion rule to cascade
For example, there will be no Cascade operations. Otherwise, they will be all deleted when the cascade operation is deleted.
1 public class Blog: BaseEntity <int> 2 {3 [Required (ErrorMessage = "{0} is Required")] 4 [Display (Name = "Blog title")] 5 [StringLength (50, ErrorMessage = "length must be less than {1} characters")] 6 public string Title {get; set ;} 7 8 [Required (ErrorMessage = "{0} is Required")] 9 [Display (Name = "Description")] 10 [StringLength (1000, errorMessage = "the length must be less than {1} characters")] 11 public string Summary {get; set ;} 12 13 [Required (ErrorMessage = "{0} is Required")] 14 public string Content {get; set ;} 15 16 [Required (ErrorMessage = "{0} is Required")] 17 [Display (Name = "Creation Time")] 18 public DateTime CreateTime {get; set ;} 19 20 [Required (ErrorMessage = "{0} is Required")] 21 [Display (Name = "")] 22 public int Volume {get; set ;} 23 24 [Display (Name = "published")] 25 public bool Publish {get; set ;} 26 27 /// <summary> 28 /// column 29 /// </summary> 30 public virtual Category. category {get; set;} 31 32 33 // public int CategoryId {get; set;} // cascade is supported if a foreign key is added. Cascade 34 is not expected here}
2 AutoMapper assigns values to existing objects
AutoMapper is a third-party ODT class library.
By default, it is assigned a value for a new object.
For example:
1 Blog blog;2 blog = Mapper.Map<Blog>(addBlogViewModel);
When our blog already has other attributes, it will also be overwritten. If we do not want to write it as follows:
Blog blog = blogManager. Find (id); // value blog = Mapper. Map <ModifyBlogViewModel, Blog> (modifyBlogViewModel, blog) based on the original object );
3. Notes for using TryUpdateModel
The following code uses TryUpdateModel to obtain Category information from the VIEW.
Category _ category = categoryManager. Find (id); if (TryUpdateModel (_ category) {An error occurred while performing the update operation}
Finally, I found that I used the attributes of the same name generated by multiple models in the view and assigned the attributes of another Model to this Model. In this example, the attributes of another Model have the same name as IDS, so an error occurred.
The code is modified as follows:
1 Category _ category = categoryManager. find (id); 2 if (TryUpdateModel (_ category, new string [] {"Type", "ParentID", "Name", "Description", "Order ", "Target"}) 3 {4. Update successful! 5}