简体   繁体   English

没有FK的实体框架中的一对多关系

[英]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. 使我感到震惊的是,B模型中缺少int外键属性。 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. 默认情况下,EntityFramework查找名称“ id”并使其成为键。 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 Microsoft延迟加载

Foreign key properties are not required by the EF. EF不需要外键属性。 EF can build hidden fields basing on object relations (and I usually use this configuration because I think is more POCO). EF可以基于对象关系建立隐藏字段(并且我通常使用此配置,因为我认为这是更多的POCO)。 The only issue is that in some cases, the exception raised during validation or SaveChanges is more cryptic, otherwise everything works fine. 唯一的问题是,在某些情况下,在验证或SaveChanges期间引发的异常更难以理解,否则一切正常。

About foreign key column names, you can configure them using fluent api (Map + MapLeftKey, MapRightKey and MapKey methods). 关于外键列名,您可以使用流利的api(Map + MapLeftKey,MapRightKey和MapKey方法)进行配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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