• 开发过程中遗漏的知识点(1)


    1 EF的级联删除

    默认情况下CodeFirst会在外键约束中设置 删除规则 为级联(不会默认设置 更新规则 为级联)
    当仅定义了导航属性如
    public virtual CategoryCategory{ get; set; }
    而没有显示定义外键如
    public int CategoryId { get; set; }
    CodeFirst不会设置 删除规则 为级联

     比如下面就不会级联 否则就是级联 删除的时候就哗哗全删了

     1 public class Blog:BaseEntity<int>
     2     {
     3        [Required(ErrorMessage = "{0}是必须的")]
     4        [Display(Name = "博客标题")]
     5        [StringLength(50, ErrorMessage = "长度必须少于{1}个字")]
     6        public string Title { get; set; }
     7 
     8        [Required(ErrorMessage = "{0}是必须的")]
     9        [Display(Name = "描述")]
    10        [StringLength(1000, ErrorMessage = "长度必须少于{1}个字")]
    11        public string Summary { get; set; }
    12  
    13        [Required(ErrorMessage = "{0}是必须的")]
    14        public string Content  { get; set; }
    15 
    16        [Required(ErrorMessage = "{0}是必须的")]
    17        [Display(Name = "创建时间")]
    18        public DateTime CreateTime { get; set; }
    19 
    20        [Required(ErrorMessage = "{0}是必须的")]
    21        [Display(Name = "阅读量")]
    22        public int Volume { get; set; }
    23 
    24         [Display(Name = "是否发布")]
    25        public bool Publish { get; set; }
    26 
    27        /// <summary>
    28        /// 栏目
    29        /// </summary>
    30        public virtual Category.Category Category { get; set; }
    31   
    32     
    33        //public int CategoryId { get; set; }  //如果显示添加外键 便支持级联 此处不希望级联
    34     }

    2 AutoMapper 给已有对象赋值

    AutoMapper 是ODT第三方类库

    他默认是new一个对象赋值的

    比如:

    1  Blog blog;
    2 blog = Mapper.Map<Blog>(addBlogViewModel);

    当我们的blog已经存在其他属性时也会覆盖 ,如果我们不希望这样就要写成:

     Blog blog = blogManager.Find(id);
    //在原对象基础上赋值
     blog = Mapper.Map<ModifyBlogViewModel, Blog>(modifyBlogViewModel, blog);

    3 使用TryUpdateModel注意点

    如下代码:我从VIEW获取 Category的信息 使用TryUpdateModel

     Category _category = categoryManager.Find(id);
     if (TryUpdateModel(_category))
      {          
               执行更新操作出错
      }

    最后发现,我在视图中使用了多个Model产生的同名属性,把另一个Model的属性赋值给了我这个Model,本例是ID同名, 所以出错。

    代码修改如下:

    1  Category _category = categoryManager.Find(id);
    2  if (TryUpdateModel(_category, new string[] { "Type", "ParentID", "Name", "Description", "Order", "Target" }))
    3 { 
    4    更新操作成功!
    5 }
  • 相关阅读:
    说说ReactiveCocoa 2
    xcode5 添加Build Phases脚本
    关于CoreData的一个工具Mogenerator的使用
    Keystone controller.py & routers.py代码解析
    Openstack Restful API 开发框架 Paste + PasteDeploy + Routes + WebOb
    Openstack Restful API 开发框架 Paste + PasteDeploy + Routes + WebOb
    Web 开发规范 — WSGI
    Web 开发规范 — WSGI
    Openstack API 类型 & REST 风格
    Openstack API 类型 & REST 风格
  • 原文地址:https://www.cnblogs.com/yhyboy/p/5859244.html
Copyright © 2020-2023  润新知