【发布时间】:2011-07-10 04:49:17
【问题描述】:
我应该如何使用 Code First 但不使用任何导航属性来定义关系?
之前我已经通过在关系的两端使用导航属性来定义 One-Many 和 Many-Many。并在数据库中创建适当的关系。这是类的简化版本(为简单起见,我已将多对多关系转换为一对多)。
public class User
{
public string UserId { get; set; }
public string PasswordHash { get; set; }
public bool IsDisabled { get; set; }
public DateTime AccessExpiryDate { get; set; }
public bool MustChangePassword { get; set; }
public virtual Role Role { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Right> Rights { get; set; }
}
public class Right
{
public Guid RightId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual Role Role { get; set; }
}
但是,如果我删除导航属性,则不会创建任何关系。下面是这些类的样子。
public class User
{
public string UserId { get; set; }
public string PasswordHash { get; set; }
public bool IsDisabled { get; set; }
public DateTime AccessExpiryDate { get; set; }
public bool MustChangePassword { get; set; }
public int Role RoleId { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Right
{
public Guid RightId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int RoleId { get; set; }
}
请注意,我有相关表的主键,而不是导航属性。一切都在桌子上创建 - 除了关系。那么我该怎么做呢?
顺便说一句,我在 dbcontext 的 OnModelCreating 方法中尝试了各种组合,但无济于事。非常感谢任何帮助!
谢谢, 梅尔
【问题讨论】:
标签: c# entity-framework entity-framework-4 code-first ef-code-first