代码之家  ›  专栏  ›  技术社区  ›  veljkoz Danko Valkov

实体框架:将实体分配给另一个实体的属性

  •  2
  • veljkoz Danko Valkov  · 技术社区  · 15 年前

    我有这些实体(这只是我为本文创建的一个抽象):

    • 语言
    • 地区
    • 说明

    这些是他们之间的参考:

    • 地区 *- 1 语言
    • 描述 *- 1 语言
    • 地区 1-1个 描述

    如果我这样拿:

    var myFetch = from c in context.Districts
                  where c.Id = 10
                  select new { DistrictId = c.Id, Lang = c.Language };
    

    在那之后,我试着把它分配给 描述 这样地:

    Description desc = Description.CreateDescription(0, "My description");
    desc.DistrictReference.EntityKey = new EntityKey("MyEntities.Descriptions", "DistrictId", myFetch.DistrictId);
    desc.Language = myFetch.Lang; //throws error
    

    引发的错误是:

    System.InvalidOperationException: 无法定义关系,因为 EntitySet名称 “myEntities.Descriptions”是 对于角色'District'无效 在关联集名称中 “MyEntities.District”描述。

    我做错什么了?

    2 回复  |  直到 15 年前
        1
  •  1
  •   mathijsuitmegen    15 年前

    如果 myFetch 将是该类的一个实例 District 你可以通过程序来做到:

    desc.DistrictReference.EntityKey = new EntityKey(  
      String.Format(  
        "{0}.{1}",   
        myFetch.EntityKey.EntityContainerName,   
        myFetch.EntityKey.EntitySetName),   
      "DistrictId", 
      myFetch.DistrictId);  
    
        2
  •  2
  •   Craig Stuntz    15 年前

    正如消息所说:您指定了错误的实体集名称。

    1. 打开你的EDMX。
    2. 打开“模型浏览器”窗口。
    3. 在模型浏览器中查找区域实体
    4. 右键单击它,选择“属性”
    5. 注意正确的实体集名称
    推荐文章