无法将关联对象正确添加到Entity Framework Context中

时间:2013-04-22 16:29:11

标签: wcf entity-framework wcf-data-services odata

我通过数据服务公开了实体框架项目:

public class VersionContext : DbContext
{
    public DbSet<VersionTreeEntry> VersionTreeEntries { get; set; }

    public DbSet<PluginState> PluginStates { get; set; }

    public static void SetForUpdates()
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<VersionContext, Configuration>());
    }
}

public class VersionTreeEntry
{
    public VersionTreeEntry()
    {
        Children = new List<VersionTreeEntry>();
        PluginStates = new List<PluginState>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public virtual ICollection<VersionTreeEntry> Children { get; set; }

    public virtual ICollection<PluginState> PluginStates { get; set; }

    public virtual VersionTreeEntry Ancestor { get; set; }

    /// <summary>
    /// Links to the ProtoBufDataItem Id for the session state.
    /// </summary>
    public int DataId { get; set; }

    public string Notes { get; set; }

    [Required]
    public DateTime TimeStamp { get; set; }

    [MinLength(1, ErrorMessage = "Tag cannot have a zero length")]
    [MaxLength(20, ErrorMessage = "A tag name cannot contain over 20 characters")]
    public string Tag { get; set; }

    public bool IsUiNodeExpanded { get; set; }

    [Required]
    public string Version { get; set; }

    [Required]
    public string SessionName { get; set; }
}

public class PluginState
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public string PluginName { get; set; }

    [Required]
    public byte[] Data { get; set; }
}

据我所知,数据类是正确定义的。我尝试创建一些新对象并将它们添加到上下文中,它们的关系保持不变:

var session = new Session();
session.SessionName = "My new session";

VersionTreeEntry versionTreeEntry = new VersionTreeEntry();
versionTreeEntry.SessionName = session.SessionName;
versionTreeEntry.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
versionTreeEntry.TimeStamp = DateTime.Now;

_versionContext.AddToVersionTreeEntries(versionTreeEntry);

foreach (var plugin in session.Plugins)
{
     using (var ms = new MemoryStream())
     {
           plugin.SaveState(ms);
           PluginState state = new PluginState();
           state.PluginName = plugin.PluginName;
           state.Data = ms.ToArray();

           versionTreeEntry.PluginStates.Add(state);
     }
}

_versionContext.SaveChanges();

问题是PluginState实例实际上从未实际添加到数据库中。如果我添加代码以手动将它们添加到上下文中,它们会被添加,但指向VersionTreeEntry的外键为null。

同样,这是一个WCF DataService而不是vanilla EF,任何想法都可能出错?

干杯

1 个答案:

答案 0 :(得分:1)

在评论部分发布答案。

同意。执行此操作的最佳方法是调用以下API:

_versionContext.AddRelatedObject(versionTreeEntry, "PluginStates", state); 

由于 PRATIK