Breeze.js实体框架多个一对一的相同类型(Parent->Child-childOne,Child-chil

Breeze.js Entity Framework multiple one to one of the same type (Parent -> Child childOne, Child childTwo)

本文关键字:Parent- gt Child-chil Child-childOne 同类型 框架 实体 js 一对一 Breeze      更新时间:2023-09-26

我确信我做错了什么,但我无法弄清楚。我使用Breezejs Todo+Knockout示例来重现我的问题。我有以下数据模型:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Todo.Models
{
  public class Parent
  {
    public Parent()
    {
    }
    [Key]
    public int Id { get; set; }
    [Required]
    public string OtherProperty { get; set; }
    public Child ChildOne { get; set; }
    public Child ChildTwo { get; set; }
  }
  public class Child
  {
    [Key]
    public int Id { get; set; }
    public int ParentId { get; set; }
    [ForeignKey("ParentId")]
    public Parent Parent { get; set; }
  }
}

在应用程序中,我执行以下操作:

breeze.NamingConvention.camelCase.setAsDefault();
var manager = new breeze.EntityManager(serviceName);
manager.fetchMetadata().then(function () {
  var parentType = manager.metadataStore.getEntityType('Parent');
  ko.utils.arrayForEach(parentType.getPropertyNames(), function (property) {
    console.log('Parent property ' + property);
  });
  var parent = manager.createEntity('Parent');
  console.log('childOne ' + parent.childOne);
  console.log('childTwo ' + parent.childTwo);
});

问题是childOne和childTwo没有定义为Parent的属性我的数据模型有问题吗日志消息为:

Parent property id
Parent property otherProperty
childOne undefined
childTwo undefined

Brock,同一类型不能有多个一对一关联。

EF不支持这种情况,原因是在一对一关系中,EF要求依赖项的主键也是外键。此外,EF无法"知道"子实体中关联的另一端(即子实体中父导航的InverseProperty是什么?-ChildOne还是ChildTwo?)

在一对一的关联中,您还必须定义主体/从属:

  modelBuilder.Entity<Parent>()
      .HasRequired(t => t.ChildOne)
      .WithRequiredPrincipal(t => t.Parent);

你可能想检查一下http://msdn.microsoft.com/en-US/data/jj591620有关配置关系的详细信息。

您可能希望有一个一对多的关联,而不是2个一对一的关系,并在代码中处理它,因此它只有2个子元素。您可能还希望在Child实体中添加一个附加属性,以确定该子项是"ChildOne"还是"ChildTwo"。