代码之家  ›  专栏  ›  技术社区  ›  Eric J.

实体框架4中的单向一对多关联?

  •  2
  • Eric J.  · 技术社区  · 14 年前

    EF4是否支持单向一对多关联,如:

    public class Parent
    {
      public int Id { get; set; }
      public string Something { get; set; }
      public List<Child> AllMyChildren { get; set; }
    }
    
    public class Child
    {
      public int Id { get; set; }
      public string Anotherthing { get; set; }
      // I don't want a back-reference to the Parent!
      // public int ParentId { get; set; }
    }
    

    当我试图用end2导航为空的父级和子级之间的关联来编译我的项目时(因为我在“添加关联”对话框中未选中end2导航属性复选框),我得到

    错误2027:没有为以下EntitySet/AssociationSet-子级指定映射。

    更新:

    如果我只是在父母身上有一个列表或类似的属性,而不是列表呢?是否需要创建一个包装类型来保存字符串,以便同时保留对父级的后向引用?

    1 回复  |  直到 12 年前
        1
  •  2
  •   DTA    13 年前

    相信使用FluentAPI(唯一消除单向关联的方法)可以实现这一点。

    modelBuilder.Entity<Child>()
    .HasKey(t => t.Id);
    
    modelBuilder.Entity<Parent>()
    .HasMany(p => p.AllMyChildren)
    .WithRequiredPrincipal();
    

    http://msdn.microsoft.com/en-us/library/hh295843(v=VS.103).aspx