首页 > 解决方案 > .Net Core 外键字段始终为空

问题描述

我们有一个 .net core api 项目。外键模型始终从选择查询返回 null。

DBContext 使用 UseLazyLoadingProxies 选项初始化。外键关系在表 ContentTopic 中定义。

外键定义为 ContentTopic->TopicId = Topic->Id

在下面的示例中,主题始终返回 null。

services.AddDbContext<VaultContext>(options =>options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DBContext")));

[Table("ContentTopic")]
public class ContentTopic
{
    [Key]
    public long Id { get; set; }
    public long TopicId { get; set; }
    public long ContentId { get; set; }
    public DateTime CreateDate { get; set; }
    public bool IsInBody { get; set; }

    [ForeignKey("TopicId")]
    public virtual Topic Topic { get; set; }
}

标签: .net-coreforeign-keysrelationship

解决方案


UseLazyLoadingProxies 扩展必须在 OnConfiguring 方法中从 DBContext 调用,而不是从 Startup.cs


推荐阅读