EF One-to-many Foreign Keys without child navigation properties

后端 未结 1 733
执念已碎
执念已碎 2021-02-20 03:59

Using code-first Entity Framework and .NET 4, I\'m trying to create a one-to-many relationship between parents to children:



        
相关标签:
1条回答
  • 2021-02-20 04:28

    First of all: You cannot use IEnumerable<T> for a collection navigation property. EF will just ignore this property. Use ICollection<T> instead.

    When you have changed this, in your particular example you don't need to do anything because the foreign key property name follows the convention (name of primary key ParentId in principal entity Parent) so that EF will detect a required one-to-many relationship between Parent and Child automatically.

    If you had another "unconventional" FK property name you still could define such a mapping with Fluent API, for example:

    public class Child
    {
        [Key]
        public int ChildId { get;  set; }
    
        public int SomeOtherId { get; set; }
    
        [Required]
        public string ChildName { get; set; }
    }
    

    Mapping:

    modelBuilder.Entity<Parent>()
        .HasMany(p => p.Children)
        .WithRequired()
        .HasForeignKey(c => c.SomeOtherId);
    

    As far as I can tell it is not possible to define this relationship with data annotations. Usage of the [ForeignKey] attribute requires a navigation property in the dependent entity where the foreign key property is in.

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