EF4 Code First:如何在不添加导航属性的情况下添加关系

我应该如何使用Code First定义关系,但不使用任何导航属性?

以前,我通过在关系的两端使用导航属性定义了“一对多”和“多对多”。 并在数据库中创build适当的关系。 这里是一个类的样子的简化版本(为了简单起见,我把多关系转换为一对多关系)。

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; } } 

但是,如果我删除导航属性,则不会创build任何关系。 这是类的样子。

 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方法中的各种组合,但无济于事。 任何帮助深表感谢!

谢谢,梅尔

我相信在使用代码优先的时候,您总是至less需要导航属性。 那么你将能够映射它:

 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); } } 

您可以使用stream利的api来添加关系,尽pipe“configuration”代码与实体代码是分开的,使得它不易被发现。

在EF 4.3中,您可以添加添加关系的迁移。