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

c# code-first entity-framework foreign-keys

Question

I'm attempting to establish a one-to-many connection between parents and children using the code-first Entity Framework with.NET 4:

public class Parent
{
    [Key]
    public int ParentId { get; set; }
    [Required]
    public string ParentName { get; set; }
    public IEnumerable<Child> Children { get; set; }
}

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

The real objects, not just their IDs, must be connected in order for the foreign key connection to be reflected in the database, as was mentioned by here. The typical method of doing this is for a youngster to mention its parent (example).

However, in the my implementation, when the parent references the kid, how do I enforce foreign keys?

1
11
5/23/2017 12:10:38 PM

Accepted Answer

Initially: You are unable to utilizeIEnumerable<T> provides a navigation property for a collection. Simply disregard this characteristic, says EF. UseICollection<T> instead.

In your specific situation, you don't need to take any action after changing this since the foreign key property name adheres to the convention (name of main key).ParentId in the main entityParent ) in order for EF to recognize the necessary one-to-many link betweenParent and Child automatically.

You could still construct such a mapping using Fluent API even if you had another "unconventional" FK property name, for instance:

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

According to what I can see, data annotations cannot be used to specify this connection. employing the[ForeignKey] the dependent item where the foreign key property is located must have a navigation property for attribute.

19
7/5/2012 8:18:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow