数据注解特性--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; }



      

    }
}
复制代码
复制代码

得到的数据库还是这个:

posted @   韩梦芫  阅读(4541)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示