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



      

    }
}

得到的数据库还是这个:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值