【发布时间】:2014-02-27 17:47:32
【问题描述】:
我正在使用 EF6 和 Database First 开发 ASP.NET MVC 项目。我正在尝试使用Redis server 来缓存常用对象。
但我在保存相关实体(父子)时遇到问题。例如下面的Author 和Author_Book 类是父子类并且相互引用(RDBMS 中的外键约束)
public partial class Author
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Author_Book> Author_Book { get; set; }
}
public partial class Author_Book
{
public int Id { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public virtual Author Author { get; set; }
}
public partial class Customer
{
public int ID { get; set; }
public string CustomerName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
查询并尝试将查询结果存储到Redis server,如下所示
using (EFTestContext db = new EFTestContext())
{
var data = db.Authors.ToList();
redisClient.Set<List<Author>>("author", data);
}
在redisClient.Set.. 的上方产生以下Exception
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
但是,如果我将客户实体(没有子实体)存储到 Redis server 中,它可以正常工作
using (EFTestContext db = new EFTestContext())
{
var customers = db.Customers.ToList();
redisClient.Set<List<Customer>>("customers", customers);
}
所以我的问题是如何将完整的实体(带子实体)存储到 redis 服务器中?
【问题讨论】:
-
试试 db.Configuration.ProxyCreationEnabled = false;
-
Author有一个Author_Book的集合并且每个Author_Book也引用Author是否有问题?我不知道 redis 客户端是如何工作的,但它可能正在尝试序列化对象图,然后遇到堆栈溢出异常。 -
@Daniel 我也认为这可能是由于该循环引用。但它是从 EF 数据库优先生成的。如果我删除循环引用,EF 开始抱怨。
-
@OferZelig 非常感谢!该链接对我很有帮助。
标签: c# asp.net-mvc entity-framework redis