【问题标题】:Relations between classes entityframeworkcore code-first类之间的关系 entityframeworkcore code-first
【发布时间】:2019-04-24 03:29:31
【问题描述】:

我是实体框架核心的初学者,但我之前通过先创建数据库使用过 Linq to SQL。 我正在尝试先用实体编写代码。

我有一个包含多个表的数据库,但无法弄清楚为什么我不能使用类之间的关系。

简单案例: 我有一个与班级用户的多对多关系相关的班级聊天。

聊天课

public int Id { get; set; }
public int StarterUserId { get; set; }
public User StarterUser { get; set; }
public int OtherUserId { get; set; }
public User OtherUser { get; set; }

用户类有一个 Id 属性。

public int Id { get; set; }
public List<Chat> InChats { get; set; }
public List<Chat> OutChats { get; set; }

而且我已经在 OnModelCreating 方法中定义了:

modelBuilder.Entity<Chat>()
            .HasOne(x => x.StarterUser)
            .WithMany(m => m.OutChats)
            .HasForeignKey(x => x.StarterUserId);
modelBuilder.Entity<Chat>()
            .HasOne(x => x.OtherUser)
            .WithMany(m => m.InChats)
            .HasForeignKey(x => x.OtherUserId);

当我得到一个 Chat 对象并观察它的属性时,我有 OtherUser 作为 User 类的对象,OtherUserId=26 (GOOD)

但我有StarterUserId=1StarterUser as null

在数据库中,我可以看到正确定义的关系。 StarterUserIdOtherUserId 都是 Users 表中的外键

这是为什么呢?我该如何解决这个问题?

已解决:我启用了延迟加载,但无法获取相关数据。

  1. 我从 nuget 安装了 Microsoft.EntityFrameworkCore.Proxies
  2. 添加我的DbContext时,我使用.UseLazyLoadingProxies()启用了延迟加载
  3. 将修改器从 public 更改为 public virtual,以获得我需要获取相关数据的属性

【问题讨论】:

  • 问题出在您的查询中,但您没有将查询添加到问题中,而是添加了很多其他代码!请将您的查询添加到问题中。
  • 我只是在 Visual Studio 中检查 Chat 对象。没有查询
  • 请检查我的答案!

标签: c# ef-code-first entity-framework-core lazy-loading eager-loading


【解决方案1】:

问题存在于您的查询中,但您没有将您的查询添加到问题中!!。我假设您缺少 eager-loading 相关实体。

因此,您必须在查询中使用.Inlcude 预先加载OtherUser,并且您的查询应如下所示:

_dbContext.Chats.Include(c => c.StarterUser)
                .Include(c => c.OtherUser).Where(c => c.Id == 1).FirstOrDefault();

更多详情:Loading Related Data in EF Core

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多