zoukankan      html  css  js  c++  java
  • 使用Code First创建数据模型

    1、声明主键

    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace MvcGuestbook.Models
    {
    public class Guestbook
    {
    [Key]
    public int No{get;set;}
    ...
    }
    }

    2、声明必填字段

    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace MvcGuestbook.Models
    {
    public class Guestbook
    {
    [Key]
    public int No{get;set;}
    [Required]
    public string Name{get;set;}
    ...
    }
    }

    3、声明允许NULL字段

    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace MvcGuestbook.Models
    {
    public class Guestbook
    {
    [Key]
    public int No{get;set;}
    [Required]
    public string Name{get;set;}
    public DateTime? CreatedOn{get;set;}
    }
    }

    4、声明字段长度

    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace MvcGuestbook.Models
    {
    public class Guestbook
    {
    [Key]
    public int No{get;set;}
    [Required]
    [MaxLength(5)]
    public string Name{get;set;}
    public DateTime? CreatedOn{get;set;}
    }
    }

    5、声明特定属性不是数据库中的字段

    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace MvcGuestbook.Models
    {
    public class Guestbook
    {
    [Key]
    public int No{get;set;}
    [Required]
    [MaxLength(5)]
    public string Name{get;set;}
    public DateTime? CreatedOn{get;set;}
    [NotMapped]
    public string FamilyName{
    get{return this.Name.Substring(0,1);}
    set{this.Name=value.Substring(0,1)+this.Name.Substring(1);}
    }
    }
    }

    6、设计模型之间的关联性

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace MvcGuestbook.Models
    {
    public class Guestbook
    {
    [Key]
    public int No{get;set;}
    
    public DateTime? CreatedOn{get;set;}
    
    public Member Menber{get;set;}
    }
    public class Member
    {
    [Key]
    public int No{get;set;}
    
    [Required]
    [MaxLength(5)]
    public string Name{get;set;}
    
    public ICollection<Guestbook> Guestbook{get;set;}
    }
    }
  • 相关阅读:
    Hibernate4集成 Annotation使用教程
    搭建SSH入过的那些坑
    Tomcat配置虚拟目录
    java中类名.class、实例.getclass()区别
    nginx使用ssl模块配置HTTPS支持
    nginx安装配置域名转发
    RedHat安装DB2详细步骤(附卸载、备份恢复步骤)
    iOS学习笔记-084.粒子效果——路径移动
    iOS APP打包上传到AppStore的最新步骤
    git使用命令, 特别:git checkout -b a 与 git branch a区别
  • 原文地址:https://www.cnblogs.com/danznb/p/3565139.html
Copyright © 2011-2022 走看看