EF一对多外键,无子导航属性 [英] EF One-to-many Foreign Keys without child navigation properties

查看:275
本文介绍了EF一对多外键,无子导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用代码优先的实体框架和.NET 4,我试图在父母与孩子之间创建一对多的关系:

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

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

正如 here ,为了使外键关系进入数据库,实际的对象必须链接,不只是他们的ID。如果一个孩子包含对其父项的引用(示例),则执行此操作的常规方法。

As pointed out here, in order for foreign key relationship to carry into the database, the actual objects must be linked, not just their IDs. The normal way to do this if for a child to contain a reference to its parent (example).

但是,如何在我的实现中强制执行外键,这是相反的方法(父引用孩子)?

But how do I enforce foreign keys in my implementation, which is the other way around (parent referencing children)?

推荐答案

首先:您不能使用 IEnumerable< T> 作为集合导航属性。 EF将忽略此属性。使用 ICollection< T>

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

当您更改此内容时,在您的具体示例中,您不需要执行任何操作,因为外键属性名称遵循约定(主键名称 ParentId 在主体实体)该EF将自动检测 Parent Child 之间所需的一对多关系。

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.

如果您有另一个非常规FK属性名称,您仍然可以使用Fluent API定义这样的映射,例如:

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

映射:

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

据我所知,无法用数据注释定义这种关系。使用 [ForeignKey] 属性需要在外键属性所在的依赖实体中的导航属性。

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.

这篇关于EF一对多外键,无子导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆