EF4 Code First: how to add a relationship without adding a navigation property

后端 未结 3 544
有刺的猬
有刺的猬 2020-11-27 20:41

How should I define relationships using Code First but without using any navigation properties?

Previously I have defined One-Many and Many-Many by using navigation

相关标签:
3条回答
  • 2020-11-27 20:57

    You can use the fluent api to add the relationship, though the "configuration" code is separate from the entity code making it less discoverable.

    0 讨论(0)
  • 2020-11-27 21:07

    I believe you always need navigation property on at least one side when using code-first. Then you will be able to map it:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 21:08

    In EF 4.3, you can add a Migration that adds the relationship.

    0 讨论(0)
提交回复
热议问题