加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 延迟加载在实体框架5中不起作用

发布时间:2020-12-16 03:15:34 所属栏目:asp.Net 来源:网络整理
导读:我在我的域项目中定义了一个(poco?)类: public class Club{ public Club() { ContactPersons = new HashSetContactPerson(); } public int Id { get; set; } [Required] [StringLength(64)] public string Name { get; set; } public virtual ICollectionC
我在我的域项目中定义了一个(poco?)类:

public class Club
{
   public Club()
   {
      ContactPersons = new HashSet<ContactPerson>();
   }

   public int Id { get; set; }

   [Required]
   [StringLength(64)]
   public string Name { get; set; }

   public virtual ICollection<ContactPerson> ContactPersons { get; set; }
}

public class ContactPerson
{
     public virtual int Id { get; set; }

     [StringLength(64)]
     public virtual string FirstName { get; set; }

     [StringLength(64)]
     public virtual string LastName { get; set; }
 }

在我的MVC项目中,我有我的clubcontroller:

public ActionResult Create(CreateClubViewModel model)
   {
      Club club = new Club();
      model.Initialize(club);
      IClubDb clubDb = DependencyResolverHelper.IClubDbService;
      clubDb.Create(club);  // create club in db
   }

    public ActionResult Display(string domain)
    {
        try
        {
            IClubDb clubDb = DependencyResolverHelper.IClubDbService;
            Club club = clubDb.Get(domain);
            return View(club);
        }
        catch (Exception)  // user is not logged iin
        {
            return View();
        }
    }

最后,在我的数据库项目中,我创建并检索了俱乐部,

public Club Get(string name)
{
   return DataContext.Clubs
   //.Include(x => x.ContactPersons)
   .Single(r => r.Name == name);
}

 public int Create(Club club)
 {
         DataContext.Clubs.Add(club);
         return DataContext.SaveChanges();
 }

当我在Display方法中调用Get俱乐部时,我已经尝试了一切让EF懒得加载我的俱乐部对象的ContactPersons但是ContactPersons的长度始终为零.但是,如果我急于使用.include加载联系人(我已经注释了这部分),那么显然ContactPersons包含许多联系人.

我不确定我做错了什么:

>我遵循了定义poco类的指南:http://msdn.microsoft.com/en-us/library/dd468057.aspx
>我有一个公共参数less constructor(但不是受保护的构造函数)
>我启用了延迟加载

我想我错过了一个概念,poco俱乐部类也是我在DB中插入的域实体.我究竟做错了什么?我不能懒得上班吗?

解决方法

尝试
????ContactPersons.ToList();

这将强制加载所有实体.
见Entity framework,when call ToList() it will load FK objects automatically?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读