繁体   English   中英

具有伪外键属性的实体框架图

[英]Entity Framework Map With Fake Foreign Key Property

我的模特:

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);

我最终收到错误消息:“类型中的每个属性名称都必须是唯一的。属性名称'other_id'已经定义。” 但是当我添加:

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

在其他配置之前,我收到错误消息:“ LINQ to Entities不支持指定的类型成员'OtherId'。仅支持初始化程序,实体成员和实体导航属性。”

那么我怎样才能使它正常工作呢? 绝对不能更改基础数据结构。

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

我建议您省略FK关系,并且当您需要手动检索两个实体时,请在您的Linq / Lambda语句中包括该联接。

您想要完成的任务没有捷径可走。 您将需要手动创建查询,类似于以下内容:

dbContext.Foos
    .GroupJoin( 
        dbContext.Bars, 
        f => f.OtherId, 
        b => b.OtherId,
        ( foo, bars ) => new { foo, bars } )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM