代码改变世界

EF框架step by step(8)—Code First DataAnnotations(2)

2011-05-14 10:58  杨延成  阅读(6360)  评论(4编辑  收藏  举报

上一篇 EF框架step by step(7)—Code First DataAnnotations(1)  描述了实体内部的采用数据特性描述与表的关系。这一篇将用DataAnnotations描述一下实体之间的关系。

ForeignKey

Code first默认情况下会自动建立实体之间的关系,比如在EF框架step by step(3)—Code-First 这篇随笔中所介绍那样。

public partial class BlogUser
{

public int BlogUserId { get; set; }
public string BlogName { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}

public partial class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public int BlogUserId { get; set; }
public virtual BlogUser BlogUser { get; set; }
}

以上这种代码写法,CodeFirst方法,在生成数据时,会在Post实体中去查找BlogUserId属性(也就是以BlogUser实体的主键),找到后,则会用此属性与BlogUser实体进行关联。如果没有找到,他会在自动创建一个列,并命名为BlogUser.BlogUserId,作为与BlogUser实体的关联属性。

用代码描述一下,将上面的代码修改成:  

public partial class BlogUser
{
public int BlogUserId { get; set; }
public string BlogName { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}

public partial class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
//期望用这个作为外键关联
public int BlogId { get; set; }
public virtual BlogUser BlogUser { get; set; }
}

但实际生成的数据表如图:

这时,可以看出,CodeFirst方法,并没有按我们所设想的那样,以BlogId做为外键,要完成这个想法,需要借助ForeignKey特性,将代码修改如下

public partial class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
//期望用这个作为外键关联
public int BlogId { get; set; }
[ForeignKey(
"BlogId")]
public virtual BlogUser BlogUser { get; set; }
}

这时,即可达到预期的目的。