虚假外键属性的实体框架图

时间:2017-06-26 19:51:58

标签: c# entity-framework linq

我的模特:

class FooEntity
{
    [Key]
    int Id { get; set; }

    [ForeignKey("Bar"), Column("other_id")]
    int OtherId { get; set; } // <-- This should be the FK

    virtual BarEntity Bar { get; set; }
}

class BarEntity
{
    [Key]
    int Id { get; set; }

    [Column("other_id")]
    int OtherId { get; set; } // <-- This is the other side of the FK
}

基本上我想重现这个SQL:

select *
from foo f
left join bar b on b.other_id = f.other_id -- AND other conditions to "guarantee" uniqueness

但是使用模型构建配置:

modelBuilder.Entity<FooEntity>()
.HasOptional(f => f.Bar)
.WithRequired()
.Map(m => m.MapKey("other_id"))
.WillCascadeOnDelete(false);

我最终得到错误:&#34;类型中的每个属性名称必须是唯一的。物业名称&#39; other_id&#39;已定义。&#34;但是当我补充说:

modelBuilder.Entity<BarEntity>().Ignore(b => b.OtherId);

在其他配置之前,我收到错误:&#34;指定的类型成员&#39; OtherId&#39; LINQ to Entities不支持。仅支持初始值设定项,实体成员和实体导航属性。&#34;

那我怎么能让这个工作?更改底层数据结构绝对不是一种选择。

2 个答案:

答案 0 :(得分:1)

  • 在EF6中,FK必须指向PK。
  • 在您的RDBMS中,它可能取决于实现。只要存在唯一索引约束,Sql Server就会允许FK返回非PK列。其他RDBMS可能允许也可能不允许。

我建议您省略FK关系,当您需要手动检索两个实体时,请在L​​inq / Lambda语句中包含连接。

答案 1 :(得分:0)

你想要完成的事情没有捷径;您将需要手动创建查询,其中包括:

UITextView