Entity Framework Code-First(9.10):DataAnnotations - NotMapped Attribute

本文介绍了如何使用DataAnnotations中的NotMappedAttribute来阻止Entity Framework Code First为指定属性创建数据库表中的列。通过具体示例展示了该属性如何应用于不需要持久化的类属性。

DataAnnotations - NotMapped Attribute:

NotMapped attribute can be applied to properties of a class. Default Code-First convention creates a column for all the properties which includes getters and setters. NotMapped attribute overrides this default convention. You can apply NotMapped attribute to a property which you do NOT want to create a column in a database table for.

Consider the following example.

using System.ComponentModel.DataAnnotations;

public class Student
{
    public Student()
    { 
        
    }

    public int StudentId { get; set; }
     
    public string StudentName { get; set; }
        
    [NotMapped]
    public int Age { get; set; }
}

 

As you can see in the above example, NotMapped attribute is applied to Age property of the Student class. So, Code First will not create a column to store Age information in the Student table as shown below.

dataannotations NotMapped attribute

Code-first also does not create a column for a property which does not have either getters or setters. Code-First will not create columns for FirstName and Age properties in the following example.

using System.ComponentModel.DataAnnotations;

public class Student
{
    public Student()
    { 
        
    }
    private int _age = 0;

    public int StudentId { get; set; }
     
    public string StudentName { get; set; }
    
    public string FirstName { get{ return StudentName;}  }
    public string Age { set{ _age = value;}  }
    
}

 

转载于:https://www.cnblogs.com/purplefox2008/p/5644209.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值