0

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

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 的外键为空。

同样,这是一个 WCF DataService 而不是普通的 EF,知道可能出了什么问题吗?

干杯

4

1 回答 1

1

从评论部分在这里发布答案。

同意。最好的方法是调用以下 API:

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

谢谢普拉蒂克

于 2013-04-25T12:28:41.033 回答