您的位置:首页 > 其它

使用Code First创建数据模型

2014-02-24 18:45 281 查看
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;}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐