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

时间:2013-08-18 17:34:50

标签: javascript breeze

我确信我做错了但我无法弄明白。我正在使用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

1 个答案:

答案 0 :(得分:0)

布洛克, 你不能有多个同一类型的一对一关联。

EF不支持这种情况,原因是在一对一关系中,EF要求从属的主键也是外键。另外,EF无法“知道”Child实体中关联的另一端(即Child实体中Parent导航的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”。