【问题标题】:Entity Framework 4 - Persisting Child Objects using only foreign keys实体框架 4 - 仅使用外键持久化子对象
【发布时间】:2011-08-19 09:04:01
【问题描述】:

我的 EF4 模型中存在多对多关系(许多组可以有许多程序)。

我有一组程序 ID 和一个组。我希望我的小组拥有由我拥有的程序 ID 表示的程序。

我不想做的是去数据库获取程序实体。我已经知道他们的身份了。

我该怎么做?

【问题讨论】:

    标签: c# .net database entity-framework orm


    【解决方案1】:

    对虚拟类使用技巧:

    // you have a group
    var group = GetGroupSomehow();
    // if group is unknown to the context Attach it
    context.Groups.Attach(group); // if it is a new group use AddObject
    // now add programs
    foreach(var program in programId.Select(id => new Program { Id = id }))
    {
        // Attach dummy program first
        context.Programs.Attach(program);
        // Now make relation between group and program
        group.Programs.Add(program);
    } 
    
    context.SaveChanges();
    

    唯一的要求是没有来自 programIds 的 Program 已经加载。如果加载了任何程序,它会更加复杂,因为您首先必须在ObjectStateManager 中检查它并使用加载的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多