三种方法:
A) 相互声明两个具有导航属性的类。在其主键上使用ForeignKey 属性标记其中一张表(从属表)。 EF 由此推断出 1 对 1:
public class AppUser
{
public int Id { get; set; }
public string Username { get; set; }
public OpenIdInfo OpenIdInfo { get; set; }
}
public class OpenIdInfo
{
[ForeignKey("AppUser")]
public int Id { get; set; }
public string OpenId { get; set; }
public AppUser AppUser { get; set; }
}
http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations。 ASPX http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx
我没用过virtual
你也不应该这样做。*
B) 声明一个继承层次结构,并明确声明两个表名,从而产生 Table-Per-Type 和共享主键。
using System.ComponentModel.DataAnnotations;
[Table("AppUser")]
public class AppUser
{
public int Id { get; set; }
public string Username { get; set; }
public OpenIdInfo OpenIdInfo { get; set; }
}
[Table("AdminUser")]
public class AdminUser : AppUser
{
public bool SuperAdmin { get; set; }
}
您将获得 2 个表:一张用于 AppUser,一张用于 AdminUser。 AdminUser 与 AppUser 是 1:1 并且是从属的 - 这意味着您可以删除 AdminUser,但如果在 AdminUser 仍指向 AppUser 时删除它,您将收到约束违反错误。
C) EF中有2种进行一对一的中途方法:
实体分裂 http://www.deliveron.com/blog/post/Entity-Splitting-in-Code-First-Entity-Framework.aspx,其中您有一个类,但它存储在主表和 1 个或多个一对一相关表中。
分表 http://www.deliveron.com/blog/post/table-splitting-in-code-first-entity-framework.aspx,其中对象树展平为单个表。例如,具有 Address 属性的类将具有 Address 对象的列,例如 Address_City,并扁平化为单个表。
*您可以在任何 EF 财产或集合中包含虚拟如果你想延迟加载它们 http://msdn.microsoft.com/en-US/data/jj574232。如果将具有延迟加载属性的对象传递给 MVC JSON 转换器或遍历对象层次结构的任何其他内容,这可能会导致无限循环或加载整个数据库。延迟加载始终同步完成,阻塞线程,并且没有任何通知。总而言之,您可以使用它来冻结代码、应用程序或服务器的方法列表很长。避免在 EF 类上使用 virtual。是的,互联网上有很多使用它的代码示例。不,你仍然不应该使用它。