【发布时间】:2020-03-02 14:44:34
【问题描述】:
我开发了一个带有实体框架的应用程序。有时我得到了
连接没有关闭。当前连接状态:正在连接
我在互联网上做了一些研究,但我无法弄清楚。如果您能提供帮助,我将不胜感激
家庭控制器:
public ActionResult Index()
{
//return View(CacheHelper.getIndexNotesFromCache()); //Yazıları son değiştirilme tarihine göre sırala ve view'e gönder
return View(noteManager.ListQueryable().Include(x=>x.Owner).Include(x=>x.Comments).Include(x=>x.Category).Include(x=>x.Likes).Where(x => x.IsDraft == false && x.IsApproved == true).OrderByDescending(x => x.ModifiedOn).Take(10).ToList());
}
我的笔记实体:
public class Note : MyEntitesBase
{
public string Tittle { get; set; }
public string Text { get; set; }
public bool IsDraft { get; set; }
public int LikeCount { get; set; }
public int CategoryID { get; set; }
public virtual EvernoteUser Owner { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual Category Category { get; set; }
public virtual List<Liked> Likes { get; set; }
public Note()
{
Comments = new List<Comment>();
Likes = new List<Liked>();
}
}
我的评论实体:
public class Comment : MyEntitesBase
{
public string Text { get; set; }
public bool CommentStatus { get; set; }
public virtual Note Note { get; set; }
public virtual EvernoteUser Owner { get; set; }
}
我的数据库上下文:
public class DatabaseContext :DbContext
{
public DbSet<EvernoteUser> EvernoteUsers { get; set; }
public DbSet<Note> Notes { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Liked> Likes { get; set; }
public DatabaseContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext,Configuration>());
Database.Initialize(force: false);
}
}
【问题讨论】:
-
我的猜测是,当您从数据库中访问信息时,这是某个时刻。您不能关闭连接。
-
首先,您正在序列化实体,这意味着对于 10 个注释中的每一个,序列化程序都需要延迟加载所有者、类别以及所有评论和喜欢。通常,尽管这会在 DbContext 被处置时表现出来,而不是处于连接状态。无论哪种方式,您都可以重新考虑将实体发送到视图,因为如果您不这样做,它的性能会更好,并且可能会避免此类问题。
-
@StevePy 我做了,但问题仍未完全解决
标签: .net asp.net-mvc database entity-framework entity