0

我正在试验 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 可以缓存它?

谢谢,

瑞克

4

1 回答 1

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());

确保该类是可序列化的

于 2010-10-07T23:11:42.293 回答