简体   繁体   中英

One-to-many relationship in Entity Framework without FK

I inherited a project with all the one to many relationships created in this fashion

[Table("A")]
public partial class A
{
    public int Id { get; set; }
    public int Something {get; set; }

    public virtual ICollection<B> B { get; set; }

}

[Table("B")]
public partial class B
{
    [Key]
    public int Id { get; set; }
    public int Something {get; set; }

    [Required]
    public virtual A A { get; set; }    
}

What struck me was the lack of a int Foreign Key property in the B model. Entity Framework must create it because they exist in our database.

Can anyone explain first why this is happening and two if this can cause problems with lazy loading?

EntityFramework by default looks for the name "id" and makes it a key. You could specify the decoration to make it faster, since it does not have to guess the key of the table.

I don't believe it affects lazy loading since lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook

Sources:
Microsoft Key
Microsoft Lazy Loading

Foreign key properties are not required by the EF. EF can build hidden fields basing on object relations (and I usually use this configuration because I think is more POCO). The only issue is that in some cases, the exception raised during validation or SaveChanges is more cryptic, otherwise everything works fine.

About foreign key column names, you can configure them using fluent api (Map + MapLeftKey, MapRightKey and MapKey methods).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM