zoukankan      html  css  js  c++  java
  • EF框架step by step(8)—Code First DataAnnotations(2)

    上一篇 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; }
    }
    复制代码

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

  • 相关阅读:
    Google Code 项目代码托管网站上 Git 版本控制系统使用简明教程
    C/C++预定义宏
    使用 Raspberry Pi 远程桌面
    Vim 中将 tab 自动转换成空格
    DR模式搭建LVS负载均衡
    NAT模式LVS搭建负载均衡集群
    php扩展memached安装
    raw_input与input的区别
    keepalived+lvs搭建高可用负载均衡集群
    使用keepalived搭建nginx高可用
  • 原文地址:https://www.cnblogs.com/Alex80/p/5141089.html
Copyright © 2011-2022 走看看