【问题标题】:I want to join 2 tables我想加入2张桌子
【发布时间】:2020-03-16 15:13:52
【问题描述】:

我正在尝试加入两个表,但遇到了一个我无法解决的错误。

var result = _context.FileModels
  .Join(_context.FilesMetaData,
  fm => fm.Id,
  fmd => fmd,
  (a, b) => new
  {
      fmId = a.Id,
      fmds = b
  });

return result;

这是错误信息:

这些是模型:

 public class FilesMetaData
    {
        public Guid Id { get; set; }
        public Guid FileId { get; set; }
        public Guid ApplicationId { get; set; }
        public string Comment { get; set; }
        public string OtherData { get; set; }
        public string AppUser { get; set; }
        public string Origin { get; set; }
        public string CreatedBy { get; set; }
        public string UpdatedBy { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
enter code here

而 FileModel 是一些具有一个索引的随机列。

【问题讨论】:

  • 修复您的数据库实体类,连接将为您完成。我发现,使用.Join 的主要原因是您的数据库中没有正确设置外键。
  • 我在 FilesMetaData 中有一个 FK(FileModels)
  • 看起来您正在使用 EntityFramework。数据库优先还是代码优先?
  • 我先用code。
  • 关系是通过 EF 中的导航属性建立的。您不应该执行连接,而是急切加载(如果需要)

标签: c# asp.net .net .net-core


【解决方案1】:

您的加入缺少一列:

.Join(_context.FilesMetaData,
  fm => fm.Id,
  fmd => fmd.FileModelId,  // <--- Define the right column

【讨论】:

  • @Ryuzake 你能发布你的课程吗,因为还有其他问题......
  • @Ryuzake 这可能会走上一条黑暗的道路,但请在您的上下文中仔细检查您的数据库集,也许跳到聊天。设置不正确,并且没有所有代码很难看到问题,并且大大改变了问题的范围。
【解决方案2】:

您似乎有外键,但导航属性在哪里?

我希望看到类似的东西:

public class FilesMetaData
{
    public Guid Id { get; set; }
    public File File {get;set;} <-- Navigation Property
    public Guid FileId { get; set; }
    public Application Application {get;set;} <-- Navigation Property
    public Guid ApplicationId { get; set; }
    ...
}
public class File
{
    public Guid Id {get;set;}
    ...
}
public class Application
{
    public Guid Id {get;set;}
    ...
}

这将在需要时自动进行连接。

【讨论】:

  • 是 IntelliSense 出了问题……我解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
相关资源
最近更新 更多