【问题标题】:How to create Navigation Properties without foreign keys and columns are named differently如何在没有外键的情况下创建导航属性,并且列的名称不同
【发布时间】:2015-08-11 19:56:11
【问题描述】:

例如我有 2 个表:

public class Entity1
{
    public decimal SodaId { get; set; }
    public virtual Entity2 Entity2 { get; set; } 
}

public class Entity2
{
    public decimal Id { get; set; }
    public string PopId { get; set; }
    public virtual ICollection<Entity1> Entity1 { get; set; }
}

1 & 2 是一对多的关系。 PopId 是 Entity1 的外键。在数据库中没有建立FK关系。而且由于列名不同,EF 不会自动看到关系。

我想为这两个表设置导航属性,但不知道如何设置?我想先使用 Fluent API 和代码。任何帮助是极大的赞赏。

【问题讨论】:

  • 请问如果您使用实体,为什么不设置FK关系?
  • 这是一个我无法控制的现有数据库。我将使用的许多表都有关系,但没有外键约束。列命名约定并不总是从一个表到另一个表匹配。
  • 您可能想查看这篇文章:Click here

标签: c# entity-framework ef-code-first navigation-properties


【解决方案1】:

在您的表格中,您说实体 2 可以有多个实体 1

public class Entity1
    {
        public decimal SodaId { get; set; }
        [ForeignKey("Entity2")]
        public int Id { get; set; }
        public virtual Entity2 Entity2 { get; set; }
    }


public class Entity2
    {
        public int Id { get; set; }
        public string PopId { get; set; }
        public virtual ICollection<Entity1> Entity1 { get; set; }
    }

这应该可以正常工作...

【讨论】:

  • 请问您为什么将 int Id 添加到实体 1 中?问题是我在数据库中实际上没有这两个表的外键,对于我将使用的许多表。虽然这两个表是相关的。 SodaId 是 1 的主键,PopId 充当 2 的外键,即使数据库中没有约束。我确实理解认为我的收藏应该在很多方面感谢这一点。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
相关资源
最近更新 更多