【问题标题】:AppFabric cache and serializing IQueryable objectsAppFabric 缓存和序列化 IQueryable 对象
【发布时间】:2011-04-22 02:58:42
【问题描述】:

我正在试验 AppFabric 缓存,但在将检索到的数据保存在缓存中时遇到了问题。问题的根源在于,AppFabric 缓存似乎要求数据将 DataContract 和 Datamember 属性应用于正在保存的类。

如果是这样,那我该如何保存(简化代码):

var q = (from u in dbContext.Users
                         select new
                         {
                             Name = u.Name,
                             Id = u.RowId
                         });

cache.Put(“test”, q.ToList());

调用 Put 会导致此异常:

System.Runtime.Serialization.InvalidDataContractException was caught
 Message=Type '<>f__AnonymousTypec`6[System.Int32,System.String,System.Nullable`1[System.Int32],System.Boolean,System.Nullable`1[System.Int32],System.Int32]' cannot 
be serialized. Consider marking it with the DataContractAttribute attribute, and 
marking all of its members you want serialized with the DataMemberAttribute 
attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft .NET Framework 
documentation for other supported types.

如何序列化 IQueryable 的结果以便 AppFabric 可以缓存它?

谢谢,

瑞克

【问题讨论】:

    标签: c# serialization appfabric netdatacontractserializer


    【解决方案1】:

    这并不是说您要执行 IQueryable,而是您的类型是匿名的。尝试为你的结果创建一个类,然后创建一个类来存储。

    [Serializable]
    public class UserIDPair
    {
        public string Name {get;set;}
        public int ID {get;set;}
    }
    
    var q = (from u in dbContext.Users
        select new UserIDPair
        {
            Name = u.Name,
            Id = u.RowId
        });
    
    cache.Put(“test”, q.ToList());
    

    确保类是可序列化的

    【讨论】:

    • 我想到了,唯一的问题是我要维护几十个这样的类。
    • 您希望如何再次将类从缓存中取出?另一种选择是在保存时动态地对对象进行 XML 序列化。您可以使用缓存对象上的辅助方法来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2014-09-13
    • 1970-01-01
    • 2010-11-03
    • 2011-04-14
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多