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;}
    }
    }
  • 相关阅读:
    Mac 终端命令大全
    美女猜拳,破解,麻麻再也不担心单机游戏的内购了
    项目CPU异常高分析
    安卓第三方动态链接库so调用,解决未对java开放的函数调用,解决类名对齐问题
    安卓动态链接库系列-编写so
    web六间房密码加密过程
    某游戏情义触发 自动化测试框架
    安卓hook
    程序安装莫名其妙失败的解决方法,程序未彻底卸载
    偶然的错误发现一个bug,引人深思的null
  • 原文地址:https://www.cnblogs.com/danznb/p/3565139.html
Copyright © 2011-2022 走看看