惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
D
Docker
Stack Overflow Blog
Stack Overflow Blog
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
H
Help Net Security
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
L
LangChain Blog
MongoDB | Blog
MongoDB | Blog
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
S
SegmentFault 最新的问题
博客园 - 司徒正美
C
Check Point Blog
B
Blog
Y
Y Combinator Blog
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
F
Fortinet All Blogs
美团技术团队
D
DataBreaches.Net

博客园 - Do you know, jack?

js继承摘要 Css中position、float和clear整理 基于组织角色的权限设计 oracle最精简客户端(3个文件+1个path变量就搞定oracle客户端) oracle客户端免安装配置、64位机器PL/SQL和VS自带的IIS连接问题 Throw与Throw ex区别,记录日志的方法 oracle数据库连接方式 允许修改Svn注释 ctrl+Enter 自动加上 .com 而不是 .com.cn google chrome服务器hosts设置 CSS文件和JS文件组织 添加NotePad++到右键菜单 960 grid system的一点研究 如何查看NHibernate中生成的SQL web页面数据验证提醒方式 The RPC server is unavailable的解决方法 编写一份代码,支持多种布署方式 为什么要使用AOP? Enterprise Library 和 Spring.Net的比较
Entity Framework关系映射容易出错的地方
Do you know, jack? · 2012-07-23 · via 博客园 - Do you know, jack?

1. 一对一关联中, 主端必须配置成Required,且类上必须用Table修饰,才能让两个类保存到同一个表中, 依赖类中主键不需要与主端的类一样,但是必须映射到同一列,同时在DbContext主端的类必须在依赖类的前面出现(下面例子中的Role必须要放在RoleProfile定义的前面)。

    public class Role
    {
        [Key]
        public int RoleId { getset; }
 
        public string RoleName { getset; }
 
        [Required]
        public RoleProfile Profile { getset; }
    }

    [Table("WF_Role")]
    public class RoleProfile
    {
        [Key, ForeignKey("MyRole"), Column("RoleId")]
        public int  Id { getset; }
        public string Country { getset; }
        public string ZipCode { getset; }

        public Role MyRole { getset; }
    } 

 2. 两个类中有多个关系时,ForeignKey要用在关联的属性上,不能用在保存到数据库的字段上,另外有一个字段要设置成可空类型,否则会提示出错

    [Table("WF_User")]
    public class User
    {
        public int UserId { getset; }

        [MaxLength(50)]
        public string UserName { getset; }
        public DateTime Birthday { getset; }
        public int Age { getset; }           

        [Column("PRole")]
        public int RoleId { getset; }

        [InverseProperty("PrimaryRoleForUsers")]
        [ForeignKey("RoleId")]
        public Role PrimaryRole { getset; }
        
        public int? SecondRoleId { getset; }

        [InverseProperty("SecondRoleForUsers")]
        [ForeignKey("SecondRoleId")]
        public Role SecondRole { getset; }
    }

    [Table("WF_Role")]
    public class Role
    {        
        [Key]
        public int RoleId { getset; }
        public string RoleName { getset; }

        public List<User> PrimaryRoleForUsers { getset; }

        public List<User> SecondRoleForUsers { getset; }        
    }

 大家可否分享一下容易出错的地方?