首页 > 解决方案 > 当两个表中都不存在 ID 时使用 Linq 连接实体框架表

问题描述

下面是我用来使用 Entity Framework 在我的数据库中生成表的类。我希望能够将此表链接到另一个表,Property. 但是,我的代码设置方式表中没有 Id 列Instruction,类中有一个 Property 属性,然后在实际数据库中生成一个 PropertyId 列,但是由于 Property 属性不是 Id 我是无法使用 Linq 加入这些表。

指令表

[Table("Instruction")]
public class Instruction
    {
        [Key]
        public int Id { get; set; }
        public InstructionTypes InstructionType { get; set; }
        public Property Property { get; set; } //Generates the EF property FK, but is not an ID so therefore cannot be used in linq.
    }

属性表

[Table("Property")]
    public partial class Property
    {
        [Key]
        public int Id { get; set; }
        public Address Correspondence { get; set; }
    }

加入查询

var instruction = 
                from instructions in _context.Instructions
                join properties in _context.Properties on instructions.Property equals properties.Id
                where ...

上面的查询给出了一个编译器错误:`join 子句中的一个表达式的类型不正确。

当我尝试使用属性对象与 propertyId 连接时,正在生成此错误。

如何更改此查询以便能够加入这两个表?

标签: c#entity-frameworklinq

解决方案


您似乎是 linq 的新手。因此,您仍然在思考,好像您仍然处于 sql 世界中。

对于实体的 linq,使用join是例外。SQL join由 EF 使用导航属性静默生成。

所以你的查询可以是:

var instruction = 
            from instruction in _context.Instructions                
            where instruction.Porperty.Correspondence.Contains("abc");

然后你可以访问

instruction.First().Property.Correspondence

作为一种好的做法,您可以将外键声明为类成员并使用 fluent API 来绑定它们。

要测试您可以使用以下代码,

//assuming that Instructions is a DbSet<Instruction>
using (var context = new MyContext() ) {
    context.Instructions.Add(
        new instruction {
            Property = new Property {
                Correspondence = new Address {}
            }
        });
}

using (var context = new MyContext() ) {
    var c = context.Instructions.First();
    console.WriteLine($"{c.Id}, {c?.Property.Id}, {c?.Property?.Correspondence.Id}");
});

推荐阅读