0

So I am just trying to get RavenDB up and running and I have struggled with several issues but finally got it working. I was able to successfully insert and pull records for display.

However, I decided to move the class I was using to generate documents from to another spot which cause a namespace change. I ran ran everything and I can still insert documents to Raven. But when I try to pull them for display purposes I get the following error:

Unable to cast object of type 'Library.Logging.RewardProviderLog' to type 'Admin.ViewModels.ImportMonitorViewModel'.

So after going through all of the other posts I could find online it seems that the issue has something to do with the Raven-Clr-Type that essentially tracks the namespace information of the object you are saving as a document.

Ok. So I went in and deleted all the documents I created since I am still just testing and trying to get things running. I even went ahead and blew away the index and recreated it. I ran my process of inserting a new log. But I still get the same error message when I try to pull them and display them.

Note: ViewModels.ImportMonitorViewModel and Library.Logging.RewardProviderLog are identical. They contain the exact same properties.

Update

Index (named ImportMonitorLogs):

from doc in docs.RewardProviderLogs 
select new {doc.status, doc.newItemsCount, doc.additionalInfo, doc.lastRun};

Query:

DocumentStore RavenDBStore = new Raven.Client.Document.DocumentStore { Url = "myurl" };
RavenDBStore.DefaultDatabase = "yei-logs";
RavenDBStore.Initialize();Raven.Client.Indexes.IndexCreation.CreateIndexes(System.Reflection.Assembly.GetCallingAssembly(), RavenDBStore);

        using(var session = RavenDBStore.OpenSession())
        {
            model = (from log in session.Query<ViewModels.ImportMonitorViewModel>("ImportMonitorLogs")
                     orderby log.lastRun descending
                     select log).ToList();
        }
4

1 回答 1

2

撇开重命名和以前可能有效的方法不谈,该错误与您尝试的查询相匹配。您正在索引 type 的文档RewardProviderLog,并将它们直接检索为 type ImportMonitorViewModel

您说两个类中的所有属性都相同,但仅凭这一点并不能让 RavenDB 为您对它们进行鸭式输入。你必须更明确一点。这可能会起作用:

model = (from log in session.Query<RewardProviderLog>("ImportMonitorLogs")
         orderby log.lastRun descending
         select log).As<ViewModels.ImportMonitorViewModel>().ToList();

或者,如果您想要更简洁的语法(恕我直言),这是等效的:

model = session.Query<RewardProviderLog>("ImportMonitorLogs")
               .OrderByDescending(x=> x.lastRun)
               .As<ViewModels.ImportMonitorViewModel>()
               .ToList();

这里的关键是您根据与您的索引返回的实体匹配的类型进行查询,并且您使用该As方法将其鸭式输入到您的视图模型中。(这与 相同,您可以在此处OfType<T>的文档中阅读更多内容)。

如果您想更高级一些并直接从索引中投影不同的字段或项目,您可以在此处AsProjection查看文档。

如果您仍然对为什么之前这样做感到头疼,我可以看到如果您的视图模型和实体被命名为相同的东西,它可能会起作用 - 即使它们来自不同的命名空间。它们仍然具有相同的Raven-Entity-Name元数据值。

于 2013-06-25T23:18:14.313 回答