如何使用Entity Framework保存和加载System.IO.Stream对象?

时间:2015-09-07 16:07:04

标签: c# wpf entity-framework telerik persistence

我想保存"视图"使用Telerik的PersistenceFramework我的wpf应用程序的状态。

我可以即时保存和加载流like in the docs examples,但我需要将status流对象存储在数据库中。

我目前正在努力尝试这些功能:

public static void SaveGridStatus(System.IO.Stream stream)
{
    using (MyEntities context = new MyEntities())
    {
        MemoryStream ms = new MemoryStream();
        stream.CopyTo(ms);
        TestViewStatus t = new TestViewStatus { GridStatus = ms.ToArray() };
        context.TestViewStatuses.Add(t);
        context.SaveChanges();
    }
}

public static Stream LoadGridStatus()
{
    using (MyEntities context = new MyEntities())
    {
        TestViewStatus t = (from d in context.TestViewStatuses
                select d).FirstOrDefault();
        return t.GridStatus;
    }
}

其中TestViewStatus.GridStatus是VARBINARY(MAX)

在数据库中保存了一些东西,但当我尝试使用持久性框架在我的控件中加载它时没有任何反应

修改

按要求将流加载到控件中的代码

private void SaveGridLayout_Click(object sender, System.Windows.RoutedEventArgs e)
{
    PersistenceManager manager = new PersistenceManager();
    this.stream = manager.Save(this.BrowseProjectGrid);
    SaveBrowseGridStatus(this.stream);
    this.EnsureLoadState();
}

private void LoadGridLayout_Click(object sender, System.Windows.RoutedEventArgs e)
{
    this.stream.Position = 0L;
    PersistenceManager manager = new PersistenceManager();
    manager.Load(this.BrowseProjectGrid, LoadBrowseGridStatus());
    this.EnsureLoadState();
}

(我想指出,如果我使用本地Stream对象来保存和检索视图状态,它可以正常工作)

1 个答案:

答案 0 :(得分:0)

我猜,那个问题在

public static Stream LoadGridStatus()
{
    using (MyEntities context = new MyEntities())
    {
        TestViewStatus t = (from d in context.TestViewStatuses
                select d).FirstOrDefault();
        return t.GridStatus;
    }
}

将其替换为

public static Stream LoadGridStatus()
{
    using (MyEntities context = new MyEntities())
    {
        TestViewStatus t = (from d in context.TestViewStatuses
                select d).FirstOrDefault();
        return new MemoryStream(t.GridStatus);
    }
}

更改是从数据库加载varbinary(max)并将其放入Stream。