gpt4 book ai didi

c# - 使用自定义列名映射外键

转载 作者:IT王子 更新时间:2023-10-29 03:57:13 26 4
gpt4 key购买 nike

我在 Oracle 中以代码优先的方式使用 Entity Framework 4.3。我收到以下错误:

System.InvalidOperationException : The ForeignKeyAttribute on property 'WidgetSequence' on type 'WidgetDistributor.WidgetEntity' is not valid. The foreign key name 'WIDGETSEQUENCE_ID' was not found on the dependent type 'WidgetDistributor.WidgetEntity'. The Name value should be a comma separated list of foreign key property names.

我的实体是这样的:

[Table("WIDGETENTITIES")]
public class WidgetEntity {

[Column("WIDGETENTITY_ID")]
public int Id { get; set; }

[ForeignKey("WIDGETSEQUENCE_ID")]
public WidgetSequence Sequence { get; set; }

// and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence {

[Column("WIDGETSEQUENCE_ID")]
public int Id { get; set; }

[Column("NUMBER")]
public int Number { get; set; }
}

我的代码似乎是正确的。我在这里做错了什么?

最佳答案

如果你不想使用流畅的语法,还有其他三种使用数据注释实现引用的方法(我个人更喜欢数据注释,因为它们看起来更容易阅读,并且写在它们所影响的属性之上):

1.1)使用 ForeignKey(具有关联属性)- 版本 1

[Table("WIDGETENTITIES")]
public class WidgetEntity {

[Column("WIDGETENTITY_ID")]
public int Id { get; set; }

[Column("WIDGETSEQUENCE_ID")]
public int WidgetSequenceId { get; set; }

[ForeignKey("WidgetSequenceId")] //Has to be a property name, not table column name
public WidgetSequence Sequence { get; set; }

// and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence {

[Column("WIDGETSEQUENCE_ID")]
public int Id { get; set; }

[Column("NUMBER")]
public int Number { get; set; }
}

1.2)使用 ForeignKey(具有关联属性)- 版本 2

[Table("WIDGETENTITIES")]
public class WidgetEntity {

[Column("WIDGETENTITY_ID")]
public int Id { get; set; }

[ForeignKey("Sequence")] //Has to be a property name, not table column name
[Column("WIDGETSEQUENCE_ID")]
public int WidgetSequenceId { get; set; }

public WidgetSequence Sequence { get; set; }

// and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence {

[Column("WIDGETSEQUENCE_ID")]
public int Id { get; set; }

[Column("NUMBER")]
public int Number { get; set; }
}

2)您还可以使用 InversePropertyAttribute。

[Table("WIDGETENTITIES")]
public class WidgetEntity {

[Column("WIDGETENTITY_ID")]
public int Id { get; set; }

[InverseProperty("WidgetEntities")]
public WidgetSequence Sequence { get; set; }

// and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence {

[Column("WIDGETSEQUENCE_ID")]
public int Id { get; set; }

[Column("NUMBER")]
public int Number { get; set; }

public virtual List<WidgetEntity> WidgetEntities { get; set; }
}

关于c# - 使用自定义列名映射外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11148662/

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