【问题标题】:Entity Framework: Assign entity to property of another entity实体框架:将实体分配给另一个实体的属性
【发布时间】:2009-09-30 14:17:45
【问题描述】:

我有这些实体(这只是我为这篇文章创建的抽象):

  • 语言
  • 说明

这些是它们之间的引用:

  • 地区 * - 1 语言
  • 描述 * - 1 语言
  • 地区 1 - 1 说明

如果我这样获取:

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

然后,我尝试将其分配给 Description,如下所示:

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: 无法定义关系,因为 实体集名称 'MyEntities.Descriptions' 是 对角色“地区”无效 在关联集名称中 'MyEntities.District_Description'。

我做错了什么?

【问题讨论】:

    标签: entity-framework entity-relationship variable-assignment entityreference


    【解决方案1】:

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

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

    【讨论】:

    • 不,事实并非如此。无论哪种方式,District 都没有在字符串中使用,所以我拼错了。
    • 是的;你只是还没有找到它。 所有 EF 名称最终会回到字符串(在 EDMX 中)。就像我说的,看看映射。描述可能是您想要的 EntitySet 名称, 但它不是您模型中的名称。
    • Argh...我把 EntityKey 放在了错误的一边......它应该是: desc.DistrictReference.EntityKey = new EntityKey("MyEntities.Districts", "Id" , myFetch.DistrictId);谢谢!
    【解决方案2】:

    如果myFetchDistrict 类的一个实例,你可以通过编程来实现:

    desc.DistrictReference.EntityKey = new EntityKey(  
      String.Format(  
        "{0}.{1}",   
        myFetch.EntityKey.EntityContainerName,   
        myFetch.EntityKey.EntitySetName),   
      "DistrictId", 
      myFetch.DistrictId);  
    

    【讨论】:

    • 我喜欢这个——它省去了拼写错误的麻烦
    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多