实体框架核心v6.0.5外国密钥属性返回意外的null

发布于 2025-01-31 08:02:01 字数 1249 浏览 0 评论 0原文

我从aspnetusers sidentityuser 的扩展名读取loginuser aspnetusers 带有实体框架核心core v6.0.5的表。

当我尝试阅读其外国密钥属性公司时,该属性始终为空 - 为什么?

IE

var user = dbContext.Users
                    .FirstOrDefault(...);// A non-null LoginUser is returned

var companyId = user.CompanyId; // results in Integer 1 - as expected

var company = user.Company; // company is always null

表定义:

public class LoginUser : IdentityUser
{
    public int CompanyId { get; set; } = -1;
    public virtual Company Company { get; set; }
}

public class Company
{
    public int Id { get; set; } = 0;
    public virtual ICollection<LoginUser> LoginUsers { get; set; }
    [Required]
    [MaxLength(128)]
    public string TradingName { get; set; } = string.Empty;
}

loginuser为列生成的company> companyId生成的外键索引。

有什么想法我要做什么?

aspnetusers表数据:

Id                                      CompanyId   Other User fields not shown...
8c568150-ecf8-46f4-8ec1-db9a7a66daaa    1   

公司表数据:

Id  TradingName 
-----------------------
-1  Unassigned Company
1   Discovery

I read a LoginUser (an extension of IdentityUser) from the AspNetUsers table with Entity Framework Core v6.0.5.

When I attempt to read its foreign key property Company, the property is always null - why?

i.e.

var user = dbContext.Users
                    .FirstOrDefault(...);// A non-null LoginUser is returned

var companyId = user.CompanyId; // results in Integer 1 - as expected

var company = user.Company; // company is always null

Table definitions:

public class LoginUser : IdentityUser
{
    public int CompanyId { get; set; } = -1;
    public virtual Company Company { get; set; }
}

public class Company
{
    public int Id { get; set; } = 0;
    public virtual ICollection<LoginUser> LoginUsers { get; set; }
    [Required]
    [MaxLength(128)]
    public string TradingName { get; set; } = string.Empty;
}

A foreign key index exists on the LoginUser table generated for the column CompanyId.

Any ideas what I have omitted to do?

AspNetUsers table data:

Id                                      CompanyId   Other User fields not shown...
8c568150-ecf8-46f4-8ec1-db9a7a66daaa    1   

Companies table data:

Id  TradingName 
-----------------------
-1  Unassigned Company
1   Discovery

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文