數據注解特性--NotMapped


NotMapped特性可以應用到領域類的屬性中,Code-First默認的約定,是為所有帶有get,和set屬性選擇器的屬性創建數據列。。

NotManpped特性打破了這個約定,你可以使用NotMapped特性到某個屬性上面,然后Code-First就不會為這個屬性就不會在數據表中創建列了。

我們看一下下面的代碼:

復制代碼
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF2
{
    [Table("StudentMaster",Schema="WaHaHa")]
   public class Student
    {
        [Key]
        [Column(Order=5)]
        public int StudentKey1 { get; set; }

        [Key]
        [Column(Order=6)]
        public int StudentKey2 { get; set; }

        
        [MaxLength(20)]
        [ConcurrencyCheck]
        [Required]
        [Column("SName",Order=1,TypeName="nvarchar")]
        public string StudentName { get; set; }

        [NotMapped()]
        public int? Age { get; set; }


        public int StandardRefId { get; set; }

        [ForeignKey("StandardRefId")]
        public virtual Standard Standard { get; set; }

      

    }
}
復制代碼

 

注意到沒有,這個表里面沒有Age列。

但是如果屬性,只有Get屬性訪問器,或者只有set屬性訪問器,那么Ef Code-First就不會為它創建數據列了。

請看:

復制代碼
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF2
{
    [Table("StudentMaster",Schema="WaHaHa")]
   public class Student
    {
        [Key]
        [Column(Order=5)]
        public int StudentKey1 { get; set; }

        [Key]
        [Column(Order=6)]
        public int StudentKey2 { get; set; }

        
        [MaxLength(20)]
        [ConcurrencyCheck]
        [Required]
        [Column("SName",Order=1,TypeName="nvarchar")]
        public string StudentName { get; set; }

        [NotMapped()]
        public int? Age { get; set; }


        public int StandardRefId { get; set; }


        public string FirstName 
        {
            get { return FirstName; }
        }

        public int myAge;
        public int MyAge 
        {
            set { value = myAge; }
        }

        [ForeignKey("StandardRefId")]
        public virtual Standard Standard { get; set; }



      

    }
}
復制代碼

得到的數據庫還是這個:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM