c# - 当两个表中都不存在 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 连接时,正在生成此错误。
如何更改此查询以便能够加入这两个表?
解决方案
您似乎是 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}");
});
推荐阅读
- angular - 如何使用 Angular 进行转换:HTML 转换为 PDF
- wpf - 转换器的生命周期是什么?
- r - 在带有刻面的箱线图中绘制替代矩形(R,ggplot2)
- powerbi - 带有 DMTS_InvalidEncryptionAlgorithmError 的 Power BI API POST 数据源错误
- regex - 如何将 textarea 标签与某个属性匹配?
- visual-studio-code - 在 VS Code 中激活扩展的菜单项在哪里?
- streaming - 查找 m3u8 文件的主主机
- r - 在不知道键的情况下使用 data.tables 进行完全外连接
- c++ - 为什么迭代器调试在调试版本中会减慢 std::unordered_map 200x?
- c# - 在 UWP desktop-bridge 包中发送语音识别 args.Result 作为参数