gpt4 book ai didi

c# - 如何使用不是第二个对象的主键的键创建导航属性?

转载 作者:行者123 更新时间:2023-11-30 18:35:01 26 4
gpt4 key购买 nike

在 EF5 中,使用代码优先方法和流畅的 API,如何基于不是另一个表的主键的键创建导航属性(多对一)?

我的数据库模型是这样的,我不能改变它:

  • TableFoo1
    • Foo1ID 整数(键)
    • 字段 1 整数
    • 值变量
  • TableFoo2
    • Foo2ID 整数(键)
    • 字段 1 整数
    • 值变量
  • 表格栏
    • BarID 整数(键)
    • 字段 1 整数
    • 值变量

我想要我的这些实体:

public class Foo1
{
public int Foo1ID { get; set; }
public int BarID { get; set; } //It corresponds Bar.ID
public string Value { get; set; }
public Bar Bar { get; set; }
}

public class Foo2
{
public int Foo2ID { get; set; }
public int BarID { get; set; } //It corresponds to Bar.Field1, NOT Bar.ID
public string Value { get; set; }
public Bar Bar { get; set; }
}

public class Bar
{
public int ID { get; set; }
public int Field1 { get; set; }
public string Value { get; set; }
}

这是我的 map (第二张是不完整的):

public  class Foo1Map : EntityTypeConfiguration<Foo1>
{
public Foo1Map()
{
this.HasKey(e => e.Foo1ID);

// Links to Bar's Primary Key, yay, it's easy.
this.HasRequired(e => e.Bar).WithMany().HasForeignKey(e => e.BarID);
}
}

public class Foo2Map : EntityTypeConfiguration<Foo2>
{
public Foo2Map()
{
this.HasKey(e => e.Foo2ID);

// No clues of how to links to Bar's other unique column, but not primary key.
this.HasRequired(e => e.Bar).WithMany()........?
}
}

public class BarMap : EntityTypeConfiguration<Bar>
{
public BarMap()
{
this.HasKey(e => e.BarID);
}
}

最佳答案

我在问题中提出的情况,其中 Foo1Foo2 都使用不同的键链接到 Bar(在 Bar 端)不能按原样在 EF5 中完成(更多细节在帖子中这个问题几乎是重复的)。但是,如果您的所有对象(此处为 Foo1Foo2)都需要映射到同一 列(具有唯一性约束),即使它是而不是映射中其他对象(此处为 Bar)的 PK,您可以将该列设置为键。此外,如果您不想对 Foo1Foo2 使用相同的列,但您永远不需要 Foo1Foo2 在上下文的相同实例中,您可以使用动态映射,但它很危险并且有很多复杂性。

关于c# - 如何使用不是第二个对象的主键的键创建导航属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15574708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com