【问题标题】:.net core 2 Entity Framework - ApplicationUser Extended Foreign Key object not populating on get.net core 2 Entity Framework - ApplicationUser 扩展外键对象未在获取时填充
【发布时间】:2019-01-22 21:26:33
【问题描述】:

我已经扩展了 ApplicationUser 以包含一个 OrganizationId 和一个应该映射到外部组织表的组织对象。这适用于初始用户注册 - 如果它是现有组织,我只需填充 OrganizationId 字段。如果它是一个新的组织,我会实例化一个新的组织对象,并在组织表中创建一个新的组织。

当我使用 GetUserAsync 提取记录时,会提取正确的 CityId 和 OrganizationId 字段。 UserCity 和 Organization 对象虽然是 NULL。我知道我可以根据返回的 ID 进行手动查找以查询城市/组织,但我想知道 Entity Framework 是否有一种机制可以在 GetUserAsync 上自动使用外键对应项填充这两个对象。

var user = await _userManager.GetUserAsync(User);

public class ApplicationUser : IdentityUser
{
    public String FirstName { get; set; }

    public String LastName { get; set; }

    public int? CityId { get; set; }

    [ForeignKey("CityId")]
    public virtual City UserCity { get; set; }

    [ForeignKey("OrganizationId")]
    public virtual Organization Organization { get; set; }

    public int? OrganizationId { get; set; }

    public bool AddToConstantContact { get; set; }
}

【问题讨论】:

  • 您找到填充外键对象的方法了吗?如果可以,请分享您的解决方案。

标签: c# .net-core entity-framework-core asp.net-core-identity .net-core-2.0


【解决方案1】:

在获取记录时,您需要使用 include 关键字来获取引用的值。例

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
    .Include(blog => blog.Posts)
    .ToList();
}

对于您的代码将类似于

context.Include("Organization").Include("City")

它也不会在实体框架核心中自动加载,因为直到版本 2.1 才支持延迟加载。

更多信息请查看https://docs.microsoft.com/en-us/ef/core/querying/related-data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多