【问题标题】:Save a foreign key, but not the whole object in WCF Data Services保存外键,但不是 WCF 数据服务中的整个对象
【发布时间】:2010-12-02 14:49:45
【问题描述】:

我正在使用 Silverlight 4、Entity Framework 4 和 WCF 数据服务。 假设我有一个播放列表对象。该播放列表对象具有属性和由显示对象的 0 到 1 导航属性表示的外键。在数据库中有一个 Display_Id 列。

我正在尝试保存播放列表并直接设置 display_id,而不是从数据库中加载整个显示对象(我从查询字符串中获取显示 id)。 我试过了:

playlist.Display = new Display() { Id = 3136 };
// this SetLink throws an exception that the Display is not yet tracked    
context.SetLink(playlist.Display, "Display", playlist);
// or i've tried, but get an error: Entities in 'EDM.Displays' participate in the //'DisplayX' relationship. 0 related 'X' were found. 1 'X' is expected
context.AddToDisplays(playlist.Display);
context.SetLink(playlist, "Display", playlist.Display);

我需要更改我的 EDM 还是有办法在客户端执行此操作?

【问题讨论】:

    标签: silverlight-4.0 entity-framework-4 wcf-data-services


    【解决方案1】:

    首先你需要将对象附加到 ObjectSet

    Display d = new Display{ id = 3136 };
    context.Displays.Attach(d);
    

    它会在本地执行而不调用数据库,然后你可以根据需要工作

    还有另一种方法:对象播放列表包含对象 DysplayReference 与属性 EntityKey 如果它是 null 然后创建它,否则只需替换 EntityKeyValues 中的键

    【讨论】:

    • 我相信 AddToDisplays 方法将它附加到上下文中。
    • 英孚帮助那些自助的人;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2012-04-18
    相关资源
    最近更新 更多