【发布时间】:2015-06-08 04:19:26
【问题描述】:
我创建了一个名为Person 的自定义类来存储姓名、地址等。这个类/模型与其他模型交叉引用,包括ApplicationUser:
public class ApplicationUser : IdentityUser
{
public Person Person { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
在我的一个控制器中,我使用以下代码让当前用户登录并获取它的 Person 对象,如下所示:
var user = UserManager.FindById(User.Identity.GetUserId());
var person = user.Person;
我的Person类也在ApplicationDbContext中定义:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MyContext", throwIfV1Schema: false)
{
}
public DbSet<Person> People { get; set; }
}
当我检查 user 时,我可以看到 Entity Framework 填充了该对象,因为我看到了用户 ID、电子邮件地址、密码哈希等所有内容!所有除了 Person 属性!但是,我可以在数据库中看到对应的行不是null,而是Person 的正确ID。
我是 ASP.NET/MVC/Entity 框架的新手,我读到它默认使用延迟加载。这是我正在经历的吗?如果是这样,我如何告诉 Entity 在Person 属性上使用预先加载?如果没有,我做错了什么?
【问题讨论】:
-
确保在
UserManager.FindById方法中分配Person属性... -
1) 您是否在
ApplicationDbContext中添加了IDbSet<Person>? & 2) 尝试将 ApplicationUser.Person 属性标记为虚拟(以便代理类可以延迟加载它)。 -- 在我看来,数据库不知道它作为一种关系存在,可能需要使用隐式约定/属性/流式模型绑定来告诉 EF。 -
@BradChristie 1) 是的,我在
ApplicationDbContext中定义了它。 2)我会尝试将其标记为虚拟。
标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-5