gpt4 book ai didi

asp.net-mvc - 延迟加载在 Entity Framework 5 中不起作用

转载 作者:行者123 更新时间:2023-12-02 13:14:27 27 4
gpt4 key购买 nike

我在我的域项目中定义了一个(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 项目中,我有我的俱乐部 Controller :

   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 Club 时,我已尝试一切方法让 EF 延迟加载我的俱乐部对象的 ContactPersons,但 ContactPersons 的长度始终为零。但是,如果我使用 .include 急切加载联系人(我已将此部分注释掉),那么显然 ContactPersons 包含许多联系人。

我不确定我做错了什么:

  1. 我遵循了定义 poco 类的准则:http://msdn.microsoft.com/en-us/library/dd468057.aspx
  2. 我有一个公共(public)无参数构造函数(但不是 protected 构造函数)
  3. 我启用了延迟加载

我认为我错过了一个概念,poco 俱乐部类也是我插入数据库的域实体。我究竟做错了什么?为什么我无法让延迟加载工作?

最佳答案

尝试一下 ContactPersons.ToList();

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

关于asp.net-mvc - 延迟加载在 Entity Framework 5 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com