我应该如何使用 Code First 但不使用任何导航属性来定义关系?
之前,我通过在关系的两端使用导航属性来定义一对多和多对多。并在数据库中创建适当的关系。这是类的精简版本(为了简单起见,我已将多对多关系转换为一对多关系)。
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 方法中尝试了各种组合,但没有成功。任何帮助深表感谢!
谢谢,
梅尔
我相信在使用代码优先时,您总是至少在一侧需要导航属性。然后你就可以映射它:
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 RoleId { get; set; }
public Role Role { 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; }
public Role Role { get; set; }
}
public class TestContext : DbContext
{
public TestContext() : base("Entities")
{}
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasRequired(r => r.Role)
.WithMany()
.HasForeignKey(r => r.RoleId);
modelBuilder.Entity<Right>()
.HasRequired(r => r.Role)
.WithMany()
.HasForeignKey(r => r.RoleId);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)